diff --git a/pt_br/full/index.adoc b/pt_br/full/index.adoc index f7b82af..e34efa0 100644 --- a/pt_br/full/index.adoc +++ b/pt_br/full/index.adoc @@ -14,7 +14,7 @@ Barry Wittman ; Tim Korb ; Aditya Mathur :xrefstyle: short :sectnums: :sectnumlevels: 3 -:listing-caption: Listing +:listing-caption: Programa ifdef::ebook-format[:leveloffset: -1] :google-analytics-account: G-VEDGKRPMMK diff --git a/pt_br/full/index.html b/pt_br/full/index.html index 546ef93..384b299 100644 --- a/pt_br/full/index.html +++ b/pt_br/full/index.html @@ -725,7 +725,7 @@

Começando Concorrente: Uma Introdução Gentil à Programação Concorrente
  • 13.2. Problema: Vírus mortal
  • 13.3. Conceitos: Dividindo para conquistar
  • 13.4. Sintaxe: Threads em Java
  • -
  • 13.5. Examples: Concurrency and speedup
  • +
  • 13.5. Exemplos: Concorrência e aceleração
  • 13.6. Concepts: Thread scheduling
  • 13.7. Syntax: Thread states
  • 13.8. Solution: Deadly virus
  • @@ -915,7 +915,7 @@

    1.2.1. Hardware

    vonNeumann
    -
    Figure 1.1 Hardware components in a typical desktop computer categorized into CPU, memory, and I/O devices.
    +
    Figura 1.1 Hardware components in a typical desktop computer categorized into CPU, memory, and I/O devices.
    CPU
    @@ -1096,7 +1096,7 @@
    Memory
    bitsBytesFigure
    -
    Figure 1.2 Shown here is a word containing four bytes, or 32 bits. Computer scientists often number items starting at zero, as we discuss in Chapter 6.
    +
    Figura 1.2 Shown here is a word containing four bytes, or 32 bits. Computer scientists often number items starting at zero, as we discuss in Chapter 6.

    Both primary and secondary storage capacities have become so large that @@ -1492,10 +1492,10 @@

    1.3.1. Compilers and interpreters

    compilerFigure
    -
    Figure 1.3 (a) Static compilation. (b) Interpreted execution. (c) Compilation into bytecode with later just-in-time compilation.
    +
    Figura 1.3 (a) Static compilation. (b) Interpreted execution. (c) Compilation into bytecode with later just-in-time compilation.
    -
    Example 1.1 Java compilation
    +
    Exemplo 1.1 Java compilation

    Java is the popular high-level programming language we focus on in @@ -1575,7 +1575,7 @@

    A few number systems
    positional number system.)

    -
    Example 1.2 Decimal numbers
    +
    Exemplo 1.2 Decimal numbers

    The number 723 can be written as @@ -1643,7 +1643,7 @@

    A few number systems
    1 ⋅ 24 = 16.

    -
    Example 1.3 Binary numbers
    +
    Exemplo 1.3 Binary numbers

    Examples of numbers written in binary are 1002, 1112, 101012, and 110000012. @@ -1669,8 +1669,8 @@

    A few number systems
    @@ -1688,7 +1688,7 @@
    A few number systems
    with only a single hexadecimal digit.

    -
    Example 1.4 Hexadecimal numbers
    +
    Exemplo 1.4 Hexadecimal numbers

    39A16, 3216, and AFBC1216 are examples of numbers written in hexadecimal. A @@ -1829,7 +1829,7 @@

    Decimal to binary conversion
    @@ -1844,7 +1844,7 @@
    Decimal to binary conversion
    division. In other words, this approach finds the digits of the binary number in backward order.

    -
    Example 1.5 Decimal to binary with remainders
    +
    Exemplo 1.5 Decimal to binary with remainders

    Let’s use this method to convert 23 to its binary equivalent. The @@ -1924,7 +1924,7 @@

    Other conversions
    @@ -2024,8 +2024,8 @@
    Other conversions
    @@ -2095,7 +2095,7 @@
    Binary arithmetic
    its presentation, we assume that the integers are represented with only 8 bits.

    -
    Example 1.6 Binary addition
    +
    Exemplo 1.6 Binary addition

    Let’s add the numbers 60 and 6 in binary. Using the conversion @@ -2173,7 +2173,7 @@

    Binary arithmetic
    position. The next example illustrates binary subtraction.

    -
    Example 1.7 Binary subtraction
    +
    Exemplo 1.7 Binary subtraction

    Again, we’ll use 60 and 6 and their binary equivalents given above.

    @@ -2214,7 +2214,7 @@
    Binary arithmetic
    @@ -2249,13 +2249,13 @@
    Negative integers in a computer
    -
    Example 1.8 Decimal to two’s complement
    +
    Exemplo 1.8 Decimal to two’s complement

    Let’s convert -29 to its binary equivalent assuming that the number will @@ -2272,12 +2272,12 @@

    Negative integers in a computer
    -
    Example 1.9 Two’s complement to decimal
    +
    Exemplo 1.9 Two’s complement to decimal

    Let’s convert the 8-bit, two’s complement value 1000 1100 to @@ -2296,7 +2296,7 @@

    Negative integers in a computer
    @@ -2318,7 +2318,7 @@
    Negative integers in a computer
    action.

    -
    Example 1.10 Two’s complement arithmetic
    +
    Exemplo 1.10 Two’s complement arithmetic

    We’ll add -126 and 126. After performing the needed conversions, their @@ -2402,7 +2402,7 @@

    Negative integers in a computer
    @@ -2423,7 +2423,7 @@
    Overflow and underflow
    number.

    -
    Example 1.11 Binary addition with overflow
    +
    Exemplo 1.11 Binary addition with overflow

    Let’s add the numbers 124 and 6. Their 8-bit, two’s complement @@ -2576,7 +2576,7 @@

    Bitwise operators
    examples follow.

    -
    Example 1.12 Bitwise operators
    +
    Exemplo 1.12 Bitwise operators

    Here are a few examples of the result of bitwise operations. We’ll @@ -2832,7 +2832,7 @@

    Fractions
    the next example.

    -
    Example 1.13 Fraction conversion to binary
    +
    Exemplo 1.13 Fraction conversion to binary

    Let’s convert 0.8125 to binary. The table below shows the steps to do @@ -2902,7 +2902,7 @@

    Fractions
    the given fraction as demonstrated in the next example.

    -
    Example 1.14 Non-terminating fraction
    +
    Exemplo 1.14 Non-terminating fraction

    Let’s convert 0.3 to binary assuming that we have only five bits in @@ -2983,8 +2983,8 @@

    Fractions
    @@ -2995,13 +2995,13 @@
    Fractions
    conversion.

    -
    Example 1.15 Rational number converted to binary
    +
    Exemplo 1.15 Rational number converted to binary

    Let’s convert 14.3 to binary assuming that we’ll only use six bits to represent the fractional part. First we convert 14 to binary using the technique described earlier. This gives us 14 = 11102. -Taking the method outlined in Example 1.14 one step further, our six bit +Taking the method outlined in Exemplo 1.14 one step further, our six bit representation of 0.3 is 0.0100112. Combining the two representations gives 14.3 = 1110.0100112.

    @@ -3044,10 +3044,10 @@
    Floating-point representation
    exponent has a bias added to it so that the result is never negative. This bias is 127 for single precision and 1,023 for double precision. The packing of the sign bit, the exponent, and the mantissa is shown in -Figure 1.4 (a) and (b).

    +Figura 1.4 (a) and (b).

    -
    Example 1.16 Single precision IEEE format
    +
    Exemplo 1.16 Single precision IEEE format

    The following is a step-by-step demonstration of how to construct the @@ -3091,7 +3091,7 @@

    Floating-point representation

    We now have the three components of 10.5 in binary. The memory -representation of 10.5 is shown in Figure 1.4 (c). +representation of 10.5 is shown in Figura 1.4 (c). Note in the figure how the sign bit, the exponent, and the mantissa are packed into 32 bits.

    @@ -3100,7 +3100,7 @@
    Floating-point representation
    @@ -3108,7 +3108,7 @@
    Floating-point representation
    numberRepresentationFigure
    -
    Figure 1.4 Layouts for floating-point representation (a) in single precision, (b) in double precision, and (c) of 10.510 in single precision.
    +
    Figura 1.4 Layouts for floating-point representation (a) in single precision, (b) in double precision, and (c) of 10.510 in single precision.
    @@ -3241,7 +3241,7 @@
    Errors in floating-point arithmeti floating-point operations are performed.

    -
    Example 1.17 Error propagation
    +
    Exemplo 1.17 Error propagation

    Suppose that the price of several products is added to determine @@ -3604,7 +3604,7 @@

    The Good
    @@ -3823,7 +3823,7 @@

    1.6. Exercises

    Create a table that lists the binary equivalents of octal digits, similar to the one in Section 1.3.2.4. Hint: Each octal digit can be represented as a sequence of three binary digits.

  • -

    Use the table from Exercise 1.10 to convert the following octal numbers to binary.

    +

    Use the table from Exercício 1.10 to convert the following octal numbers to binary.

    1. @@ -3930,12 +3930,12 @@

      1.6. Exercises

  • -

    Expand Example 1.14 assuming that you have ten bits to represent the +

    Expand Exemplo 1.14 assuming that you have ten bits to represent the fraction. Convert the representation back to base 10. How far off is this value from 0.3?

  • -

    Will the process in Example 1.14 ever terminate, assuming that we can use as +

    Will the process in Exemplo 1.14 ever terminate, assuming that we can use as many bits as needed to represent 0.3 in binary? Why or why not?

  • @@ -4304,7 +4304,7 @@

    2.2.1. Software development lifecycle

  • -
    Example 2.1 Rising costs of fixing an error
    +
    Exemplo 2.1 Rising costs of fixing an error

    Imagine that your company works on computer-aided design (CAD) software. @@ -4344,7 +4344,7 @@

    2.2.1. Software development lifecycle

    -
    Example 2.2 Ball bouncing problem and plan
    +
    Exemplo 2.2 Ball bouncing problem and plan

    Recall the statement of the problem from the Problem section:

    @@ -4368,7 +4368,7 @@

    2.2.1. Software development lifecyclehc2 the second time. By examining this pattern for the third and fourth bounce, it becomes clear that the ball will bounce to a height of hck on the -kth time. See Figure 2.1 +kth time. See Figura 2.1 for a graphic description of this process.

    @@ -4382,7 +4382,7 @@

    2.2.1. Software development lifecycle bouncingBall

    -
    Figure 2.1 A ball is dropped from height h. The ball rises to height hc after the first bounce and to hc2 after the second.
    +
    Figura 2.1 A ball is dropped from height h. The ball rises to height hc after the first bounce and to hc2 after the second.
  • @@ -4408,7 +4408,7 @@

    2.2.1. Software development lifecycleDisplay the calculated height.

    The solution to each of the three subproblems requires input and -generates an output. Figure 2.2 shows how these +generates an output. Figura 2.2 shows how these solutions are connected. The first box in this figure represents the solution to subproblem 1. It asks a user to input values of parameters h, c, and k. It sends these @@ -4421,7 +4421,7 @@

    2.2.1. Software development lifecycle subProblemRelation

    -
    Figure 2.2 Connections between solutions to the three subproblems in the bouncing ball problem.
    +
    Figura 2.2 Connections between solutions to the three subproblems in the bouncing ball problem.

  • @@ -4612,7 +4612,7 @@

    2.3.1. Java program structure

    @@ -4881,20 +4881,20 @@
    The Scanner class
    -
    Example 2.3 Command line input
    +
    Exemplo 2.3 Command line input

    Subproblem 1 requires us to get the height, coefficient of restitution, -and number of bounces from the user. Program 2.1 +and number of bounces from the user. Programa 2.1 shows a Java program to solve this subproblem.

    -
    Program 2.1 A Java program to get the height, coefficient of restitution, and number of bounces from the command line.
    +
    Programa 2.1 A Java program to get the height, coefficient of restitution, and number of bounces from the command line.
    import java.util.*; (1)
     
    @@ -4972,14 +4972,14 @@ 
    The Scanner class
    -
    Example 2.4 Input for distance computation
    +
    Exemplo 2.4 Input for distance computation

    Let’s write a program that takes as input the speed of a moving object @@ -5004,11 +5004,11 @@

    The Scanner class
    -

    Program 2.2 solves each of these subproblems in order, +

    Programa 2.2 solves each of these subproblems in order, using the command-line input and output tools we have just discussed.

    -
    Program 2.2 Computes the distance a moving object travels.
    +
    Programa 2.2 Computes the distance a moving object travels.
    import java.util.*; (1)
     
    @@ -5124,13 +5124,13 @@ 

    2.3.3. GUI input and output

    -

    Figure 2.3 shows what the resulting GUI might look like.

    +

    Figura 2.3 shows what the resulting GUI might look like.

    showMessageDialog
    -
    Figure 2.3 Example of showMessageDialog() used for output.
    +
    Figura 2.3 Example of showMessageDialog() used for output.

    One way to do input with a GUI uses the showInputDialog() method, @@ -5160,14 +5160,14 @@

    2.3.3. GUI input and output

    Note that whatever the user typed in will be stored in word. Finally, the last line of the program displays this information with -showMessageDialog(). Figure 2.4 shows the +showMessageDialog(). Figura 2.4 shows the GUI as the user is entering input.

    showInputDialog
    -
    Figure 2.4 Example of showInputDialog() used for input.
    +
    Figura 2.4 Example of showInputDialog() used for input.

    Remember that the value returned from the showInputDialog() method is @@ -5212,15 +5212,15 @@

    2.3.3. GUI input and output

    bouncing ball problem.

    -
    Example 2.5 GUI input
    +
    Exemplo 2.5 GUI input
    -

    We can change the solution given in Program 2.1 to +

    We can change the solution given in Programa 2.1 to use the GUI-based input tools in JOptionPane. -Program 2.3 is the equivalent GUI-based Java program.

    +Programa 2.3 is the equivalent GUI-based Java program.

    -
    Program 2.3 Gets the height, coefficient of restitution, and number of bounces using a GUI.
    +
    Programa 2.3 Gets the height, coefficient of restitution, and number of bounces using a GUI.
    import javax.swing.*;
     
    @@ -5321,7 +5321,7 @@ 
    Other operations
    -
    Example 2.6 Compute height
    +
    Exemplo 2.6 Compute height

    We compute the final height of the ball in subproblem 2 of the bouncing @@ -5330,7 +5330,7 @@

    Other operations
    The following program does so, using the Math.pow() method.

    -
    Program 2.4 Computes height of a ball after bounces.
    +
    Programa 2.4 Computes height of a ball after bounces.
    public class ComputeHeight {
         public static void main(String[] args) {
    @@ -5345,7 +5345,7 @@ 
    Other operations
    -

    Program 2.4 is only focusing on subproblem 2, but, +

    Programa 2.4 is only focusing on subproblem 2, but, if we want to test it, we need to supply some dummy values for height, coefficient, and bounces, since these are read in by the solution to subproblem 1. Likewise, the output statement on the last line of the @@ -5385,7 +5385,7 @@

    String concatenation
    -
    Example 2.7 Display height
    +
    Exemplo 2.7 Display height

    With String concatenation, subproblem 3 becomes a bit easier. We @@ -5393,7 +5393,7 @@

    String concatenation
    use the System.out.println() method for output.

    -
    Program 2.5 Displays height of a ball using the command line.
    +
    Programa 2.5 Displays height of a ball using the command line.
    public class DisplayHeightCLI {
         public static void main(String[] args) {
    @@ -5408,7 +5408,7 @@ 
    String concatenation
    -

    Program 2.5 is only focusing on subproblem 3, +

    Programa 2.5 is only focusing on subproblem 3, but if we want to test it, we need to supply dummy values for bounces and bounceHeight, since these are generated by the solution to earlier subproblems.

    @@ -5419,7 +5419,7 @@
    String concatenation
    JOptionPane.showMessageDialog() instead of System.out.println().

    -
    Program 2.6 Displays height of a ball using a GUI.
    +
    Programa 2.6 Displays height of a ball using a GUI.
    import javax.swing.*;
     
    @@ -5725,15 +5725,15 @@ 

    2.4. Solution: How to solve problems

    2.4.1. Bouncing ball solution (command line version)

    -

    In Example 2.2, we made sure +

    In Exemplo 2.2, we made sure we understood the problem and then formed a three-part plan to read in the input, compute the height of the bounce, and then output it.

    -

    In Program 2.1, we implemented subproblem 1, reading -the input from the command line. In Program 2.4, +

    In Programa 2.1, we implemented subproblem 1, reading +the input from the command line. In Programa 2.4, we implemented subproblem 2, computing the height of the final bounce. -In Program 2.5, we implemented subproblem 3, +In Programa 2.5, we implemented subproblem 3, displaying the height that was computed. In the final, integrated program, the portion of the code that corresponds to solving subproblem 1 is below.

    @@ -5795,12 +5795,12 @@

    2.4.2. Bouncing ball solution (GUI

    If you prefer a GUI for your input and output, we can integrate the GUI-based versions of the solutions to subproblems 1, 2, and 3 from -Program 2.1, Program 2.4, and -Program 2.6. The final program is below. It only +Programa 2.1, Programa 2.4, and +Programa 2.6. The final program is below. It only differs from the command line version in a few details.

    -
    Program 2.7 Full program to compute the height of the final bounce of a ball and display the result with a GUI.
    +
    Programa 2.7 Full program to compute the height of the final bounce of a ball and display the result with a GUI.
    import javax.swing.*;
     
    @@ -5915,13 +5915,13 @@ 

    2.5.2. Sequential versus conc save the people of Earth, it’s imperative that you translate their demands as quickly as possible so world leaders can choose a course of action. If you do it alone, as illustrated in -Figure 2.5(a), the Lellaraps might attack +Figura 2.5(a), the Lellaraps might attack before you finish.

    In order to finish the work faster, you hire a second translator whose skills in Lellarap are as good as yours. As shown in -Figure 2.5(b), you divide the document into +Figura 2.5(b), you divide the document into two nearly equal parts, Document A and Document B. You translate Document A, and your colleague translates Document B. When both translations are complete, you merge the two, check the translation, and @@ -5931,7 +5931,7 @@

    2.5.2. Sequential versus conc
    documentTranslationFigure
    -
    Figure 2.5 (a) Translation by one translator. Time ts gives the sequential time taken. (b) Translation by translators A and B. Times t1, t2, t3, and t4 give the times needed to do each component of the concurrent approach.
    +
    Figura 2.5 (a) Translation by one translator. Time ts gives the sequential time taken. (b) Translation by translators A and B. Times t1, t2, t3, and t4 give the times needed to do each component of the concurrent approach.

    Translating the demands alone is a sequential approach. In this @@ -5944,7 +5944,7 @@

    2.5.2. Sequential versus conc

    If you wrote a computer program to translate the demands using the sequential approach, you’d produce a sequential program. If you wrote a computer program that uses the approach shown in -Figure 2.5(b), it would be a concurrent +Figura 2.5(b), it would be a concurrent program. A concurrent program is also referred to as a multi-threaded program. Threads are sequences of code that can execute independently and access each other’s memory. Imagine you’re one thread of execution @@ -5954,16 +5954,16 @@

    2.5.2. Sequential versus conc

    Because we’re interested in the time the process takes, we’ve labeled -different tasks in Figure 2.5 with their +different tasks in Figura 2.5 with their running times. We let ts be the time for one person to complete the translation. The times t1 through t4 mark the times needed to complete tasks 1 through 4, -indicated in Figure 2.5(b).

    +indicated in Figura 2.5(b).

    @@ -5987,19 +5987,19 @@

    2.5.3. Kinds of concurrency

    examples explore each of these approaches.

    -
    Example 2.8 Domain decomposition
    +
    Exemplo 2.8 Domain decomposition

    Suppose we have an autonomous robot called the Room Rating Robot or R3. The R3 can measure the area of any home. Suppose that we want to use an R3 to measure the area of the home with two floors sketched in -Figure 2.6.

    +Figura 2.6.

    floorPlan
    -
    Figure 2.6 A home with two floors.
    +
    Figura 2.6 A home with two floors.

    One way to measure the area is to put an R3 at the entrance of the @@ -6050,7 +6050,7 @@

    2.5.3. Kinds of concurrency

    @@ -6069,7 +6069,7 @@

    2.5.3. Kinds of concurrency

    @@ -6081,10 +6081,10 @@

    2.5.3. Kinds of concurrency

    next example illustrates such a division.

    -
    Example 2.9 Task decomposition
    +
    Exemplo 2.9 Task decomposition
    -

    Let’s expand the problem given in Example 2.8. R3 robots can do more than just measure area. In +

    Let’s expand the problem given in Exemplo 2.8. R3 robots can do more than just measure area. In addition to calculating the living area of a home, we want an R3 robot to check if the electrical outlets are in working condition. The robot should give us the area of the house as well as a list of electrical @@ -6153,13 +6153,13 @@

    2.7. Exercises

    solved by the program written by the programmer? Are they the same?

  • -

    In Program 2.2, we declared all variables to be of type +

    In Programa 2.2, we declared all variables to be of type double. How would the program behave differently if we had declared all the variables with type int?

  • What is the purpose of the statement Scanner in = new Scanner(System.in); in -Program 2.1?

    +Programa 2.1?

  • Explain the difference between a declaration and an assignment @@ -6167,7 +6167,7 @@

    2.7. Exercises

  • Is the following -statement from Program 2.7 a declaration, an assignment, or a +statement from Programa 2.7 a declaration, an assignment, or a combination of the two?

    @@ -6184,12 +6184,12 @@

    2.7. Exercises

  • Review -Program 2.7 and identify all the Java keywords +Programa 2.7 and identify all the Java keywords used in it.

  • Try to recompile -Program 2.7 after removing the import +Programa 2.7 after removing the import statement at the top. Read and explain the error message generated by the compiler.

  • @@ -6201,7 +6201,7 @@

    2.7. Exercises

  • Refer to -Figure 2.5. Suppose that you and your +Figura 2.5. Suppose that you and your colleague translate from English to Lellarapian at the rate of 200 words per hour. Suppose that the list of demands contains 10,000 words.

    @@ -6243,12 +6243,12 @@

    2.7. Exercises

  • In -Example 2.8, what aspect of a multicore +Exemplo 2.8, what aspect of a multicore system do the robots represent?

  • In -Example 2.8, suppose that you have two R3 +Exemplo 2.8, suppose that you have two R3 robots available. You’d like to use them to measure the living area of a single-floor home. Suggest how two robots could be programmed to work concurrently to measure the living area faster than one.

    @@ -6269,32 +6269,32 @@

    2.7. Exercises

  • Expand the program from -Exercise 2.13 so that it finds the average of +Exercício 2.13 so that it finds the average of the three numbers instead of the sum. (Hint: Try dividing by 3.0 instead of 3 to get an average with a fractional part. Then, store the result in a variable of type double.)

  • -

    Rewrite your solution to Exercise 2.14 so +

    Rewrite your solution to Exercício 2.14 so that it uses a JOptionPane-based GUI instead of Scanner and System.out.print().

  • Copy and paste -Program 2.1 into the Java IDE you prefer. Compile +Programa 2.1 into the Java IDE you prefer. Compile and run it and make sure that the program executes as intended. Then, add statements to prompt the user for the color of the ball and read it in. Store the color in a String value. Add an output statement that mentions the color of the ball.

  • -

    Rewrite your solution to Exercise 2.16 +

    Rewrite your solution to Exercício 2.16 so that it uses a JOptionPane-based GUI instead of Scanner and System.out.print().

  • -

    In Example 2.4, we assumed that the speed is given in miles -per hour and the time in hours. Change Program 2.2 to +

    In Exemplo 2.4, we assumed that the speed is given in miles +per hour and the time in hours. Change Programa 2.2 to compute the distance traveled by a moving object given its speed in miles per hour but time in seconds. You will need to perform a conversion from seconds to hours before you can find the distance.

    @@ -6514,7 +6514,7 @@

    3.2.1. Types as sets and operations

    3.2.2. Primitive and reference types in Java

    -

    As shown in Figure 3.1(a), there are two kinds of +

    As shown in Figura 3.1(a), there are two kinds of types in Java: primitive types and reference types. Primitive types are like boxes that hold single, concrete values. The primitive types in Java are byte, short, int, long, float, double, boolean, @@ -6528,7 +6528,7 @@

    3.2.2. Primitive and reference t
    typesInJavaFigure
    -
    Figure 3.1 (a) The two categories of types in Java. The int primitive type (b), the boolean primitive type (c), the String reference type (d), and a possible Aircraft reference type (e) are represented as sets of items with operations.
    +
    Figura 3.1 (a) The two categories of types in Java. The int primitive type (b), the boolean primitive type (c), the String reference type (d), and a possible Aircraft reference type (e) are represented as sets of items with operations.

    Reference types work differently from primitive types. For one thing, a @@ -6588,7 +6588,7 @@

    3.2.2. Primitive and reference t @@ -6782,7 +6782,7 @@

    Integers: byte, sh from each type are given below.

    - +@@ -6838,7 +6838,7 @@
    Integers: byte, sh @@ -6856,7 +6856,7 @@
    Integers: byte, sh clear purpose.

    -
    Example 3.1 Integer variables
    +
    Exemplo 3.1 Integer variables

    Consider the following declarations.

    @@ -6948,7 +6948,7 @@
    Floating-point numbers: float.

    -
    Example 3.2 Floating-point declarations
    +
    Exemplo 3.2 Floating-point declarations

    Consider the following declarations.

    @@ -6986,7 +6986,7 @@
    Accuracy in number representation
    -
    Example 3.3 Floating-point accuracy
    +
    Exemplo 3.3 Floating-point accuracy

    Try executing the following statements within a Java program.

    @@ -7251,7 +7251,7 @@
    Precedence
    a + (b / c) but different from (a + b) / c.

    -
    Example 3.4 Order of operations
    +
    Exemplo 3.4 Order of operations

    Consider the following lines of code.

    @@ -7664,12 +7664,12 @@
    Bitwise operators
    -
    Example 3.5 Binary operators in Java
    +
    Exemplo 3.5 Binary operators in Java

    The following code shows a sequence of bitwise operations performed with @@ -7743,7 +7743,7 @@

    Casting
    types.

    -
    Example 3.6 Upcast with integers
    +
    Exemplo 3.6 Upcast with integers

    Consider the following statements.

    @@ -7767,7 +7767,7 @@
    Casting
    -
    Example 3.7 Downcast error
    +
    Exemplo 3.7 Downcast error

    Consider these statements that declare variables a, b, and c and @@ -7806,12 +7806,12 @@

    Casting
    -
    Example 3.8 Upcast from integers to floating-point
    +
    Exemplo 3.8 Upcast from integers to floating-point

    Integers are automatically converted to floating-point when needed. @@ -7852,7 +7852,7 @@

    Casting
    type int.

    -
    Example 3.9 Downcast from double to int
    +
    Exemplo 3.9 Downcast from double to int

    The following statements cause a compiler error because an expression @@ -7916,12 +7916,12 @@

    Casting
    -
    Example 3.10 Conversion from double to float
    +
    Exemplo 3.10 Conversion from double to float

    Consider the following declaration and assignment of variable @@ -7965,7 +7965,7 @@

    Casting
    @@ -8090,7 +8090,7 @@
    Characters: char
    16 × 6 + 4 = 100, which is the letter 'd'.

    -
    Example 3.11 Printing single characters
    +
    Exemplo 3.11 Printing single characters

    If you print a char variable or literal directly, it prints the @@ -8194,7 +8194,7 @@

    Booleans: boolean
    Table 3.1 Ranges for primitive integer types in Java.Tabela 3.1 Ranges for primitive integer types in Java.
    -
    Example 3.12 Boolean variables
    +
    Exemplo 3.12 Boolean variables

    The following declarations and assignments illustrate some uses of @@ -8336,7 +8336,7 @@

    3.3.3. Reference types

    wombat
    -
    Figure 3.2 Two Wombat references pointing at the same object.
    +
    Figura 3.2 Two Wombat references pointing at the same object.

    Then, anything we do to w1 will affect w2 and vice versa. For @@ -8370,7 +8370,7 @@

    3.3.3. Reference types

    primitive
    -
    Figure 3.3 Because they’re primitive, int variables store values, not references.
    +
    Figura 3.3 Because they’re primitive, int variables store values, not references.

    Now that we’ve highlighted some of the differences between primitive and @@ -8393,7 +8393,7 @@

    String basics
    @@ -8410,12 +8410,12 @@
    String basics
    -
    Example 3.13 String assignment
    +
    Exemplo 3.13 String assignment

    The following declarations define two String references named @@ -8459,7 +8459,7 @@

    String operations
    String class defines many more.

    -
    Example 3.14 String concatenation
    +
    Exemplo 3.14 String concatenation

    Here’s another example of combining String objects using the + @@ -8541,7 +8541,7 @@

    String operations
    used.

    -
    Example 3.15 Examining the char value at an index
    +
    Exemplo 3.15 Examining the char value at an index

    To see what char is at a given location, we call charAt() with the @@ -8588,7 +8588,7 @@

    String operations
    substring from an existing String.

    -
    Example 3.16 Retrieving a substring
    +
    Exemplo 3.16 Retrieving a substring

    You can generate a substring of a String (which is, itself, a String) using the @@ -8617,7 +8617,7 @@

    String operations
    of a substring, as shown in the next example.

    -
    Example 3.17 String search
    +
    Exemplo 3.17 String search

    Suppose we wish to find a String inside of another String. To do so, @@ -8734,7 +8734,7 @@

    Comparison
    other. The following gives examples of these comparisons.

    -
    Example 3.18 Comparison
    +
    Exemplo 3.18 Comparison

    Consider the following lines of code.

    @@ -8764,7 +8764,7 @@
    Comparison
    differentObjectsFigure
    -
    Figure 3.4 Objects thing1, thing2, and thing3 (a) in their initial states and (b) after the assignment thing1 = thing2;.
    +
    Figura 3.4 Objects thing1, thing2, and thing3 (a) in their initial states and (b) after the assignment thing1 = thing2;.

    This code declares and initializes three String values. Although it’s @@ -8798,7 +8798,7 @@

    Comparison

    To better understand comparison between reference types, consider -Figure 3.4(a), which shows three different +Figura 3.4(a), which shows three different objects. Note that each reference points at a distinct object, even though two objects have the same contents.

    @@ -8811,7 +8811,7 @@
    Comparison
    -

    As shown in Figure 3.4(b), this assignment points +

    As shown in Figura 3.4(b), this assignment points reference thing1 to the same location as reference thing2. Then, (thing1 == thing2) would be true.

    @@ -8835,7 +8835,7 @@
    Comparison
    @@ -8916,7 +8916,7 @@

    3.4.1. The Math library

    Math documentation.

    - +@@ -8991,7 +8991,7 @@

    3.4.1. The Math library

    Table 3.2 A sample of methods available in the Java Math class. Arguments to trigonometric methods are given in radians.Tabela 3.2 A sample of methods available in the Java Math class. Arguments to trigonometric methods are given in radians.
    -
    Example 3.19 Math library usage
    +
    Exemplo 3.19 Math library usage

    Here’s a program that uses the Math.pow() method to compute compound @@ -9000,7 +9000,7 @@

    3.4.1. The Math library

    statement.

    -
    Program 3.1 Computes interest earned and new balance.
    +
    Programa 3.1 Computes interest earned and new balance.
    import java.util.*;
     
    @@ -9122,15 +9122,15 @@ 

    3.4.2. Random numbers

    video game.

    -
    Example 3.20 Dragon attribute generation
    +
    Exemplo 3.20 Dragon attribute generation

    Suppose you’re designing a video in which the hero must fight a dragon -with random attributes. Program 3.2 generates +with random attributes. Programa 3.2 generates random values for the age, height, gender, and hit points of the dragon.

    -
    Program 3.2 Sets attributes of a randomly generated dragon for a video game.
    +
    Programa 3.2 Sets attributes of a randomly generated dragon for a video game.
    import java.util.*; (1)
     
    @@ -9185,7 +9185,7 @@ 

    3.4.2. Random numbers

    Because we are using random values, the output of -Program 3.2 changes every time we run the +Programa 3.2 changes every time we run the program. Sample output is given below.

    @@ -9242,7 +9242,7 @@
    String to numerical conve

    A common task for a wrapper class is to convert a String representation of a number such as "37" or "2.097" to its corresponding numeric value. We had such a situation in -Program 2.3, where we did the conversion as follows.

    +Programa 2.3, where we did the conversion as follows.

    @@ -9265,7 +9265,7 @@
    String to numerical conve using three of these methods.

    -
    Example 3.21 String to numeric conversion
    +
    Exemplo 3.21 String to numeric conversion

    Consider the following statements that show how a string can be @@ -9296,7 +9296,7 @@

    String to numerical conve @@ -9497,7 +9497,7 @@
    Maximum and minimum values
    @@ -9514,8 +9514,8 @@
    Maximum and minimum values
    @@ -9790,7 +9790,7 @@

    3.6.1. Splitting expressions

    answer. The following example illustrates these steps.

    -
    Example 3.22 Split expression
    +
    Exemplo 3.22 Split expression

    Consider the following statement:

    @@ -9803,29 +9803,29 @@

    3.6.1. Splitting expressions

    This statement evaluates methods f() and g(), multiplies the computed values, and assigns the result to variable value. In -Figure 3.5, we show two ways of evaluating the -expression f(a,b)*g(c). Figure 3.5(a) shows +Figura 3.5, we show two ways of evaluating the +expression f(a,b)*g(c). Figura 3.5(a) shows sequential evaluation of the expression, where f() is computed, g() follows, and then the two results are multiplied to get the final value. -Figure 3.5(b) shows evaluation of the expression +Figura 3.5(b) shows evaluation of the expression in which f() and g() are evaluated concurrently instead.

    splitExpressionFigure
    -
    Figure 3.5 Computation of value = f(a,b)*g(c) with (a) sequential and (b) concurrent approaches.
    +
    Figura 3.5 Computation of value = f(a,b)*g(c) with (a) sequential and (b) concurrent approaches.

    On a multicore processor, the computation of f() and g() could be carried out on separate cores. We can create one thread for each method and wait for the threads to complete. Upon completion, we can retrieve the results of each computation and multiply them together as in -Figure 3.5(b). Program 3.3 +Figura 3.5(b). Programa 3.3 illustrates this concurrent approach.

    -
    Program 3.3 Concurrent evaluation of an expression.
    +
    Programa 3.3 Concurrent evaluation of an expression.
    public class SplitExpression {
         public static void main(String[] args) {
    @@ -9885,7 +9885,7 @@ 

    3.6.1. Splitting expressions

    7 Once the threads have completed their respective tasks, the execution of -Program 3.3 resumes, and we obtain the result of the +Programa 3.3 resumes, and we obtain the result of the computation done by fThread by calling its getResult() method. @@ -9911,7 +9911,7 @@

    3.6.1. Splitting expressions

    If you don’t understand all the elements of -Program 3.3, don’t despair! We’re trying to give +Programa 3.3, don’t despair! We’re trying to give you an example of what concurrency looks like in Java, but you can’t be expected to master all the details at this stage. However, concurrency in Java will often follow the steps shown:

    @@ -10007,7 +10007,7 @@

    3.8. Exercises

    int and long?

  • -

    In Example 3.7, the sum +

    In Exemplo 3.7, the sum of two int variables was another int value, which could not be stored into a byte variable. Would this code have worked if variables a and b had been declared with type byte? What if a was assigned @@ -10195,7 +10195,7 @@

    3.8. Exercises

    For each of the following expressions, determine the maximum amount of concurrency that can be achieved. Using a diagram similar to -Figure 3.5(b), show how the computation of each +Figura 3.5(b), show how the computation of each expression will proceed. Assume there are no side effects. Note that you can create separate threads for multiple instances of method f().

    @@ -10878,14 +10878,14 @@

    4.3.1. if statements

    Chapter 8 and Chapter 9. What we’re focusing on now is that the line umbrella.take(); is executed only if raining has the value true. Nothing is done if it’s false. -Figure 4.1 shows this pattern of conditional execution +Figura 4.1 shows this pattern of conditional execution followed by all if statements.

    if
    -
    Figure 4.1 Execution goes inside the if statement when its condition is true and skips past it otherwise.
    +
    Figura 4.1 Execution goes inside the if statement when its condition is true and skips past it otherwise.

    Our descriptions of logical scenarios from the previous section used the @@ -10971,14 +10971,14 @@

    4.3.1. if statements

  • -

    Figure 4.2 shows the pattern of conditional execution +

    Figura 4.2 shows the pattern of conditional execution followed by all if statements that have a matching else statement.

    else
    -
    Figure 4.2 Execution goes inside the if statement when its condition is true and jumps into the else statement otherwise.
    +
    Figura 4.2 Execution goes inside the if statement when its condition is true and jumps into the else statement otherwise.
    @@ -11225,7 +11225,7 @@

    4.3.2. The boolean ty mathematical context.

    - +@@ -11395,7 +11395,7 @@

    4.3.2. The boolean ty also use some methods from class Math.

    -
    Example 4.1 Leap year
    +
    Exemplo 4.1 Leap year

    In the standard Gregorian calendar, leap years occur roughly once every @@ -11422,7 +11422,7 @@

    4.3.2. The boolean ty 100.

    -
    Program 4.1 Prompts the user for a year and then determines whether or not it is a leap year.
    +
    Programa 4.1 Prompts the user for a year and then determines whether or not it is a leap year.
    import java.util.*;
     
    @@ -11457,7 +11457,7 @@ 

    4.3.2. The boolean ty

    -
    Example 4.2 Quadratic formula
    +
    Exemplo 4.2 Quadratic formula

    The quadratic formula is a useful tool from mathematics. Using this @@ -11479,7 +11479,7 @@

    4.3.2. The boolean ty these three possibilities into account.

    -
    Program 4.2 Solves a quadratic equation.
    +
    Programa 4.2 Solves a quadratic equation.
    import java.util.*;
     
    @@ -11553,7 +11553,7 @@ 

    4.3.2. The boolean ty

    -
    Example 4.3 20 Questions
    +
    Exemplo 4.3 20 Questions

    In the time-honored game of 20 Questions, one person mentally chooses @@ -11577,7 +11577,7 @@

    4.3.2. The boolean ty
    flowchart
    -
    Figure 4.3 Decision tree to distinguish 10 items.
    +
    Figura 4.3 Decision tree to distinguish 10 items.

    Using these items, we can construct a tree of decisions, @@ -11587,10 +11587,10 @@

    4.3.2. The boolean ty dolphin. If it’s not a mammal, we could ask if it flies, deciding between an eagle and a lizard. We can construct similar questions for the things in the vegetable and mineral categories, matching -Figure 4.3.

    +Figura 4.3.

    -
    Program 4.3 Navigates the possible choices in the decision tree.
    +
    Programa 4.3 Navigates the possible choices in the decision tree.
    import java.util.*;
     
    @@ -12030,7 +12030,7 @@ 

    4.3.3. switch statements

    switch statements.

    -
    Example 4.4 Days in the month
    +
    Exemplo 4.4 Days in the month

    There are fewer uses for switch statements than if statements. @@ -12041,7 +12041,7 @@

    4.3.3. switch statements

    that maps the number of the month to the number of days it contains.

    -
    Program 4.4 Computes the number of days in a given month.
    +
    Programa 4.4 Computes the number of days in a given month.
    import java.util.*;
     
    @@ -12106,7 +12106,7 @@ 

    4.3.3. switch statements

    -
    Example 4.5 Ordinal numbers
    +
    Exemplo 4.5 Ordinal numbers

    The term ordinal numbers refers to numbers that are used for ordering @@ -12126,7 +12126,7 @@

    4.3.3. switch statements

    give the correct ordinal endings for most numbers as follows.

    -
    Program 4.5 Appends the appropriate suffix to a numeral to make it an ordinal.
    +
    Programa 4.5 Appends the appropriate suffix to a numeral to make it an ordinal.
    import java.util.*;
     
    @@ -12162,12 +12162,12 @@ 

    4.3.3. switch statements

    -
    Example 4.6 Astrology
    +
    Exemplo 4.6 Astrology

    Many cultures practice astrology, a tradition that the time of a @@ -12257,7 +12257,7 @@

    4.3.3. switch statements

    correctly output the animal corresponding to an input birth year.

    -
    Program 4.6 Determines a Chinese zodiac animal based on birth year.
    +
    Programa 4.6 Determines a Chinese zodiac animal based on birth year.
    import java.util.*;
     
    @@ -12373,7 +12373,7 @@ 

    4.3.3. switch statements

    statements for each month to test the exact range of dates.

    -
    Program 4.7 Determines Western zodiac signs based on birth month and day.
    +
    Programa 4.7 Determines Western zodiac signs based on birth month and day.
    import java.util.*;
     
    @@ -12779,7 +12779,7 @@ 

    4.6. Exercises

  • The calculation to determine the leap year given in -Example 4.1 uses three if statements and three +Exemplo 4.1 uses three if statements and three else statements. Write the leap year calculation using a single if and a single else. Feel free to use boolean connectors such as || and &&.

    @@ -12925,11 +12925,11 @@

    4.6. Exercises

  • -

    Re-implement both parts from Exercise 4.10 using switch statements instead of if statements.

    +

    Re-implement both parts from Exercício 4.10 using switch statements instead of if statements.

  • Expand the program given in -Example 4.5 to give the correct suffixes (always +Exemplo 4.5 to give the correct suffixes (always “th”) for numbers that end in 11, 12, and 13. Use the modulus operator to find the last two digits of the number. Using an if statement, a switch statement, or a combination, check for those three @@ -13300,14 +13300,14 @@

    5.3.1. while loops

    afterward. This similarity is not accidental. The only difference between the two is that the body of the if statement will run a only single time, while the body of the while loop will run as long as the -condition remains true. Figure 5.1 shows the pattern of +condition remains true. Figura 5.1 shows the pattern of execution for while loops.

  • while
    -
    Figure 5.1 If the condition is true, all of the statements in the body of the loop are executed, and then the condition is checked again. When the check is false, execution skips past the body of the loop.
    +
    Figura 5.1 If the condition is true, all of the statements in the body of the loop are executed, and then the condition is checked again. When the check is false, execution skips past the body of the loop.

    If we assume that the boolean value atDoor says whether or not we @@ -13391,7 +13391,7 @@

    5.3.1. while loops

    binary representation of a number.

    -
    Example 5.1 Binary Conversion
    +
    Exemplo 5.1 Binary Conversion

    As we discussed in Chapter 1, binary numbers @@ -13425,7 +13425,7 @@

    5.3.1. while loops

    definition of a number written in base 2.

    -
    Program 5.1 Outputs a binary representation of a decimal number.
    +
    Programa 5.1 Outputs a binary representation of a decimal number.
    import java.util.*;
     
    @@ -13515,14 +13515,14 @@ 

    5.3.2. for loops

    The header of a for loop consists of those three parts: the initialization, the condition, and the update, all separated by -semicolons. Figure 5.2 shows the pattern of execution for +semicolons. Figura 5.2 shows the pattern of execution for for loops.

    for
    -
    Figure 5.2 The loop is initialized. If the condition is true, all of the statements in the body of the loop are executed, followed by the increment step. Then the condition is checked again. When the check is false, execution skips past the body of the loop.
    +
    Figura 5.2 The loop is initialized. If the condition is true, all of the statements in the body of the loop are executed, followed by the increment step. Then the condition is checked again. When the check is false, execution skips past the body of the loop.

    You may have noticed that we changed the variable name used within @@ -13667,7 +13667,7 @@

    5.3.2. for loops

    applications, since it’s more general and more readable.

    -
    Example 5.2 Primality testing
    +
    Exemplo 5.2 Primality testing

    Prime numbers are integers greater than 1 whose only factors are 1 and themselves. @@ -13685,7 +13685,7 @@

    5.3.2. for loops

    must be prime. Here is this basic solution.

    -
    Program 5.2 Gives a naive approach for testing if a number is prime.
    +
    Programa 5.2 Gives a naive approach for testing if a number is prime.
    import java.util.*;
     
    @@ -13720,7 +13720,7 @@ 

    5.3.2. for loops

    can do half the checking with a few simple modifications.

    -
    Program 5.3 Gives a slightly cleverer approach for testing if a number is prime.
    +
    Programa 5.3 Gives a slightly cleverer approach for testing if a number is prime.
    import java.util.*;
     
    @@ -13767,7 +13767,7 @@ 

    5.3.2. for loops

    the square root of n, which will save much more time.

    -
    Program 5.4 Gives a much faster approach for testing if a number is prime.
    +
    Programa 5.4 Gives a much faster approach for testing if a number is prime.
    import java.util.*;
     
    @@ -13798,12 +13798,12 @@ 

    5.3.2. for loops

    -
    Example 5.3 DNA reverse complement
    +
    Exemplo 5.3 DNA reverse complement

    DNA is usually double stranded, with each base paired to another @@ -13862,7 +13862,7 @@

    5.3.2. for loops

    manipulations on it to get the reverse complement.

    -
    Program 5.5 Finds the reverse complement of a DNA sequence.
    +
    Programa 5.5 Finds the reverse complement of a DNA sequence.
    import java.util.*;
     
    @@ -13910,7 +13910,7 @@ 

    5.3.2. for loops

    a separate step.

    -
    Program 5.6 More cleverly finds the reverse complement of a DNA sequence.
    +
    Programa 5.6 More cleverly finds the reverse complement of a DNA sequence.
    import java.util.*;
     
    @@ -13955,14 +13955,14 @@ 

    5.3.3. do-while loops

    that guarantee. The syntax for a do-while loop is a do at the top of a loop body enclosed in braces, with a normal while header at the end, including a condition in parentheses, followed by a semicolon. -Figure 5.3 shows the pattern of execution for do-while +Figura 5.3 shows the pattern of execution for do-while loops.

    dowhile
    -
    Figure 5.3 The statements in the body of the loop are executed, and then the condition is checked. When the check is false, execution skips past the body of the loop. A do-while loop is guaranteed to run at least once.
    +
    Figura 5.3 The statements in the body of the loop are executed, and then the condition is checked. When the check is false, execution skips past the body of the loop. A do-while loop is guaranteed to run at least once.

    We can use a do-while loop to print out the first 10 perfect squares @@ -14050,7 +14050,7 @@

    5.3.4. Nested loops

    will be added by the System.out.println() method in the outer loop.

    -
    Example 5.4 Triangular numbers
    +
    Exemplo 5.4 Triangular numbers

    The sequence consisting of 1, 3, 6, 10, 15, and so on is known as the @@ -14064,7 +14064,7 @@

    5.3.4. Nested loops

    triangular numbers, where n is specified by the user.

    -
    Program 5.7 Prints out triangular numbers.
    +
    Programa 5.7 Prints out triangular numbers.
    import java.util.*;
     
    @@ -14095,7 +14095,7 @@ 

    5.3.4. Nested loops

    i to it, as i increases.

    -
    Program 5.8 Prints out triangular numbers more cleverly.
    +
    Programa 5.8 Prints out triangular numbers more cleverly.
    import java.util.*;
     
    @@ -14554,7 +14554,7 @@ 

    5.4. Solution: DNA searching

    @@ -14655,7 +14655,7 @@

    5.5. Concurrency: Loops

    only the power of loops, you can see parallelism in action now.

    -
    Example 5.5 Parallelism without threads
    +
    Exemplo 5.5 Parallelism without threads

    Consider the problem of computing the sum of the sines of a range of @@ -14673,7 +14673,7 @@

    5.5. Concurrency: Loops

    output around this loop.

    -
    Program 5.9 Adds the sines of all integers in a range specified by the user.
    +
    Programa 5.9 Adds the sines of all integers in a range specified by the user.
    import java.util.Scanner;
     
    @@ -14736,7 +14736,7 @@ 

    5.5. Concurrency: Loops

    to balance out the workload.

    -

    This sines example is similar to Example 13.10 in Chapter 13. +

    This sines example is similar to Exemplo 13.10 in Chapter 13. As you may have noticed, running four programs simultaneously is not convenient. You have to open several windows, you have to type starting and ending points very carefully, and you have to combine the answers at the end since @@ -14749,7 +14749,7 @@

    5.5. Concurrency: Loops

    @@ -14767,7 +14767,7 @@

    5.6. Exercises

    of the three kinds of loops would you use, and why?

  • -

    In Example 5.2, +

    In Exemplo 5.2, our last version of the primality tester PrimalityTester2 computes the square root of the number being tested. Instead of computing this value before the loop, how would performance be affected by changing the head @@ -14913,7 +14913,7 @@

    5.6. Exercises

    an int?

  • -

    In Example 5.2, we gave three programs to +

    In Exemplo 5.2, we gave three programs to test a number for primality. Run each of these prime testers on a large prime such as 982,451,653 and time them. Is there a significant difference in the running time of PrimalityTester0 and @@ -14921,9 +14921,9 @@

    5.6. Exercises

    PrimalityTester2?

  • -

    In Example 5.5, we ran four programs at the same time to solve a +

    In Exemplo 5.5, we ran four programs at the same time to solve a problem in parallel. Use the same framework (combined with your -knowledge of primes from Example 5.2) to write +knowledge of primes from Exemplo 5.2) to write a program that can see how many prime numbers are in a user specified range of integers. Then, use it to find the total number of primes between 2 and 500,000,000. Now, run two copies of the program with one @@ -14997,7 +14997,7 @@

    6.2. Problem: Game of Life

    cell
    -
    Figure 6.1 Cell (shown in gray) surrounded by 8 neighboring cells.
    +
    Figura 6.1 Cell (shown in gray) surrounded by 8 neighboring cells.
  • The pattern of alive and dead cells at any given time on the grid is @@ -15309,7 +15309,7 @@

    6.4.1. Array declaration and insta
    array
    -
    Figure 6.2 Array elements showing index values.
    +
    Figura 6.2 Array elements showing index values.

    Whenever an array is instantiated, each of its n elements @@ -15367,7 +15367,7 @@

    6.4.2. Indexing into arrays

    array2
    -
    Figure 6.3 Array showing contents of elements.
    +
    Figura 6.3 Array showing contents of elements.

    The key thing to understand about indexing into an array is that it @@ -15597,7 +15597,7 @@

    6.4.4. Redirecting input

    summing all the numbers it gets as input.

    -
    Program 6.1 Sums a list of numbers given as input.
    +
    Programa 6.1 Sums a list of numbers given as input.
    import java.util.*;
     
    @@ -15644,7 +15644,7 @@ 

    6.4.4. Redirecting input

    gives the total count of numbers.

    -
    Program 6.2 Sums a list of numbers given as input without prompting the user.
    +
    Programa 6.2 Sums a list of numbers given as input without prompting the user.
    import java.util.*;
     
    @@ -15701,7 +15701,7 @@ 

    6.5. Examples: Array usage

    a task that searches for words, like a dictionary look up.

    -
    Example 6.1 King of the hill
    +
    Exemplo 6.1 King of the hill

    Finding the largest value input by a user is not difficult. Applying @@ -15762,7 +15762,7 @@

    6.5. Examples: Array usage

    -
    Example 6.2 Selection sort
    +
    Exemplo 6.2 Selection sort

    Sorting is the bread and butter of computer scientists. Much research @@ -15902,7 +15902,7 @@

    6.5. Examples: Array usage

    -
    Example 6.3 Word search
    +
    Exemplo 6.3 Word search

    In this example, we read in a list of words and a long passage of @@ -16070,12 +16070,12 @@

    6.5. Examples: Array usage

    -
    Example 6.4 Statistics
    +
    Exemplo 6.4 Statistics

    Imagine you’re a teacher who has just given an exam. You want to @@ -16121,7 +16121,7 @@

    6.5. Examples: Array usage

    Table 4.1 Relational operatorsTabela 4.1 Relational operators
    -

    Example 6.1 covered how to find the maximum and +

    Exemplo 6.1 covered how to find the maximum and minimum scores in a list. The mean is simply the sum of all the scores divided by the total number of scores. Standard deviation is a little bit trickier. It gives a measurement of how spread out the data is. Let @@ -16343,7 +16343,7 @@

    6.5. Examples: Array usage

    @@ -16829,7 +16829,7 @@

    6.7.2. Reference types

    array3
    -
    Figure 6.4 Two array references pointing to a single array object.
    +
    Figura 6.4 Two array references pointing to a single array object.

    Sometimes this reference feature of Java allows us to write code that is @@ -17178,7 +17178,7 @@

    6.8. Examples: Two-dimensional arrays< vector multiplication useful in math, and finish with a game.

    -
    Example 6.5 Calendar
    +
    Exemplo 6.5 Calendar

    We’re going to create a calendar that can be printed to the terminal to @@ -17190,7 +17190,7 @@

    6.8. Examples: Two-dimensional arrays< falls under the appropriate day of the week.

    -
    Program 6.3 Prints a calendar for a given month, formatted week by week.
    +
    Programa 6.3 Prints a calendar for a given month, formatted week by week.
    import java.util.*;
     
    @@ -17279,7 +17279,7 @@ 

    6.8. Examples: Two-dimensional arrays<

    -
    Example 6.6 Matrix-vector multiplication
    +
    Exemplo 6.6 Matrix-vector multiplication

    Arrays give a natural way to represent vectors and matrices. In 3D @@ -17315,7 +17315,7 @@

    6.8. Examples: Two-dimensional arrays< x-axis by the amount specified by the user.

    -
    Program 6.4 Uses matrix multiplication to rotate a point in three-dimensional space.
    +
    Programa 6.4 Uses matrix multiplication to rotate a point in three-dimensional space.
    import java.util.*;
     
    @@ -17386,7 +17386,7 @@ 

    6.8. Examples: Two-dimensional arrays<

    -
    Example 6.7 Tic-Tac-Toe
    +
    Exemplo 6.7 Tic-Tac-Toe

    Almost every child knows the game of tic-tac-toe, also known as noughts and crosses. @@ -17605,7 +17605,7 @@

    6.8. Examples: Two-dimensional arrays< @@ -17957,7 +17957,7 @@

    6.10. Solution: Game of Life

    @@ -18009,7 +18009,7 @@

    6.11. Concurrency: Arrays

    @@ -18028,10 +18028,10 @@

    6.11. Concurrency: Arrays

    split1
    -
    Figure 6.5 Units of work per thread using a naive strategy.
    +
    Figura 6.5 Units of work per thread using a naive strategy.
    -
    Example 6.8 Fairly assigning work
    +
    Exemplo 6.8 Fairly assigning work

    A simple way to fix this problem is to look at the value @@ -18050,13 +18050,13 @@

    6.11. Concurrency: Arrays

    split2
    -
    Figure 6.6 Units of work per thread using a fair strategy.
    +
    Figura 6.6 Units of work per thread using a fair strategy.

    The program below reads the length of an array and the number of threads from the user and then prints out the amount of work for each one. You should be able to adapt the ideas in it to your own multi-threaded programs in Chapter 13.

    -
    Program 6.5 Template for assigning work to threads.
    +
    Programa 6.5 Template for assigning work to threads.
    import java.util.*;
     
    @@ -18185,11 +18185,11 @@ 

    6.12. Exercises

    1. -

      In Example 6.3, +

      In Exemplo 6.3, our code would not count ship, as an occurrence of ship because of the comma.

      -

      Rewrite the code from Example 6.3 to remove +

      Rewrite the code from Exemplo 6.3 to remove punctuation from the beginning and end of a word. Use a loop that runs as long as the character at the beginning of a word is not a letter, replacing the word with a substring of itself that does not include the @@ -18199,7 +18199,7 @@

      6.12. Exercises

    2. -

      In Example 6.3, we +

      In Exemplo 6.3, we wrote a program that counts the occurrences of each word from a list within a text. If the list of words to search within is long, it can take quite some time to search through the entire list. If the list of @@ -18215,8 +18215,8 @@

      6.12. Exercises

      to find an element in a list of n items. In contrast, looking through the list one element at a time takes about n comparisons.

      -

      Rewrite the code from Example 6.3 to use binary -search, after applying selection sort from Example 6.2. Although selection sort will take some extra time, you should +

      Rewrite the code from Exemplo 6.3 to use binary +search, after applying selection sort from Exemplo 6.2. Although selection sort will take some extra time, you should more than make up the difference with such a fast search. To implement binary search, keep variables for the start, middle, and end of the list. Keep adjusting the three variables until the middle index has the @@ -18225,7 +18225,7 @@

      6.12. Exercises

    3. -

      In Example 6.4, we gave a program that finds the +

      In Exemplo 6.4, we gave a program that finds the maximum, minimum, mean, standard deviation, and median of a list of values. Another statistic that is sometimes important is the mode, or most commonly occurring element. For example, in the list @@ -18238,7 +18238,7 @@

      6.12. Exercises

    4. We used the example of tic-tac-toe in -Example 6.7 because a more complex game would have +Exemplo 6.7 because a more complex game would have taken too much space to solve. The game of Connect Four (or the Captain’s Mistress, as it was originally called) pits two players against each other on a 6 × 7 vertical board. One @@ -18300,7 +18300,7 @@

      6.12. Exercises

    5. Run the implementation of the word search program using the binary -search improvement from Exercise 6.9. Use the OS +search improvement from Exercício 6.9. Use the OS time command to time the difference between the regular and binary search versions of the program with a long list of words. You may see very little difference on small input, but you can easily find a list of @@ -18314,7 +18314,7 @@

      6.12. Exercises

      Generate input files consisting of 1,000, 10,000, and 100,000 random int values. Time our implementation of selection sort from -Example 6.2 running on each of these input files +Exemplo 6.2 running on each of these input files and redirecting output to output files. What’s the behavior of the running time as the input length increases by a factor of 10? As a function of n, how many times total does the body of the inner @@ -18409,13 +18409,13 @@

      7.2. Concepts: User interaction

      GUIs.

    -
    Example 7.1 User interaction
    +
    Exemplo 7.1 User interaction
    -

    Figure 7.1(a) shows a Java application +

    Figura 7.1(a) shows a Java application interacting with a user through a command line interface. The application asks the user for a temperature value in degrees Fahrenheit, -converts it to the equivalent Celsius, and displays it. Figure 7.1(b) shows a +converts it to the equivalent Celsius, and displays it. Figura 7.1(b) shows a similar application interacting with the user through a GUI. In this case, the application creates a window with six widgets (two labels, two text boxes, and two buttons). The user enters a temperature value in the text box @@ -18427,7 +18427,7 @@

    7.2. Concepts: User interaction

    applicationInterface
    -
    Figure 7.1 User interaction with a Java application (a) through a command line interface and (b) through a graphical user interface.
    +
    Figura 7.1 User interaction with a Java application (a) through a command line interface and (b) through a graphical user interface.
    @@ -18459,21 +18459,21 @@

    7.3. Syntax: Dialogs and the

    An information, or message, dialog displays a message to the user. Static method showMessageDialog() creates such a dialog. See -Figure 7.2 for an example of a message dialog.

    +Figura 7.2 for an example of a message dialog.

    Confirm

    A confirm dialog asks a user to confirm a statement. Static method
    showConfirmDialog() creates such a dialog. This dialog may return user input as YES_OPTION, NO_OPTION, OK_OPTION, or -CANCEL_OPTION. See Figure 7.4 for an example of +CANCEL_OPTION. See Figura 7.4 for an example of a Yes-No dialog.

    Option

    An option dialog asks the user to select one from an arbitrary set of options. Static method showOptionDialog() creates such a dialog. See -Figure 7.5 for an example.

    +Figura 7.5 for an example.

    Input
    @@ -18505,7 +18505,7 @@

    7.3. Syntax: Dialogs and the @@ -18520,16 +18520,16 @@

    7.3.1. Generating an information dialog

    purpose is to inform the user that a task has been completed.

    -
    Example 7.2 Simple dialog
    +
    Exemplo 7.2 Simple dialog
    -

    Program 7.1 creates a dialog to inform the user +

    Programa 7.1 creates a dialog to inform the user that the task it was assigned to perform is now complete. -Figure 7.2 shows the dialog generated by this +Figura 7.2 shows the dialog generated by this program.

    -
    Program 7.1 Generates a simple dialog.
    +
    Programa 7.1 Generates a simple dialog.
    import javax.swing.*; (1)
     
    @@ -18607,7 +18607,7 @@ 

    7.3.1. Generating an information dialog

    -

    In Figure 7.2 the dialog titled “Simple Dialog” +

    In Figura 7.2 the dialog titled “Simple Dialog” includes an icon, a message, and a button labeled “OK.” This dialog is actually a frame, which is what windows are called in Java. We’ll discuss frames in greater detail in Section 15.3.

    @@ -18616,7 +18616,7 @@

    7.3.1. Generating an information dialog

    simpleMessageFigure
    -
    Figure 7.2 A simple dialog generated using JOptionPane.
    +
    Figura 7.2 A simple dialog generated using JOptionPane.

    The appearance of the dialog may be different on your @@ -18652,7 +18652,7 @@

    7.3.1. Generating an information dialog

    When used as parameters in showMessageDialog(), the constants above cause different default icons to be displayed in the dialog box. -Figure 7.3 shows dialogs generated by +Figura 7.3 shows dialogs generated by showMessageDialog() when using JOptionPane.ERROR_MESSAGE, (left) and JOptionPane.WARNING_MESSAGE (right). Note the difference in the icons displayed toward the top left of the two dialogs.

    @@ -18661,12 +18661,12 @@

    7.3.1. Generating an information dialog

    iconsinMessageDialogsFigure
    -
    Figure 7.3 The left dialog uses JOptionPane.ERROR_MESSAGE, and the right uses JOptionPane.WARNING_MESSAGE. The only difference is the icon displayed.
    +
    Figura 7.3 The left dialog uses JOptionPane.ERROR_MESSAGE, and the right uses JOptionPane.WARNING_MESSAGE. The only difference is the icon displayed.
    @@ -18679,7 +18679,7 @@

    7.3.2. Generating a Yes-No confirm dialog

    such a dialog and how to get the user’s response.

    -
    Example 7.3 Yes-No dialog
    +
    Exemplo 7.3 Yes-No dialog

    Consider a program that checks whether a student understands the @@ -18687,11 +18687,11 @@

    7.3.2. Generating a Yes-No confirm dialog

    integer x, presents it to the user, and asks the question, “Is x an odd integer?” The answer given by the user is checked for correctness, and the user is informed accordingly. -Program 7.2 shows how to use the JOptionPane class +Programa 7.2 shows how to use the JOptionPane class to generate a dialog for such an interaction.

    -
    Program 7.2 Tests knowledge of odd and even integers with a Yes-No dialog.
    +
    Programa 7.2 Tests knowledge of odd and even integers with a Yes-No dialog.
    import javax.swing.*;
     import java.util.*;
    @@ -18728,14 +18728,14 @@ 

    7.3.2. Generating a Yes-No confirm dialog

    We present the number to the user. Note the use of JOptionPane.YES_NO_OPTION as the last parameter in the showConfirmDialog(). The generated -dialog is shown in Figure 7.4(a). The call to +dialog is shown in Figura 7.4(a). The call to showConfirmDialog() returns the JOptionPane.YES_OPTION or the JOptionPane.NO_OPTION value depending on whether the user clicked the “Yes” or “No” button. 3 -A second dialog is shown with a message dependent on whether the user gives the correct answer. The two different versions of this dialog are shown in Figure 7.4(b) and (c). +A second dialog is shown with a message dependent on whether the user gives the correct answer. The two different versions of this dialog are shown in Figura 7.4(b) and (c).
    @@ -18743,13 +18743,13 @@

    7.3.2. Generating a Yes-No confirm dialog

    yes noDialogFigure
    -
    Figure 7.4 (a) A Yes-No dialog generated using JOptionPane. (b) Dialog in response to correct answer. (c) Dialog in response to incorrect answer.
    +
    Figura 7.4 (a) A Yes-No dialog generated using JOptionPane. (b) Dialog in response to correct answer. (c) Dialog in response to incorrect answer.

    Because we used YES_NO_OPTION, the dialog in -Example 7.3 automatically generates two buttons +Exemplo 7.3 automatically generates two buttons labeled “Yes” and “No.” Dialogs can also use the YES_NO_CANCEL_OPTION to generate a dialog with “Yes,” “No,” and “Cancel” options. The return value from showConfirmDialog() is @@ -18758,8 +18758,8 @@

    7.3.2. Generating a Yes-No confirm dialog

    @@ -18771,7 +18771,7 @@

    7.3.3. Generating a dialog options as shown in the next example.

    -
    Example 7.4 Capital dialog
    +
    Exemplo 7.4 Capital dialog

    Consider a program that asks the user to select the correct capital of a @@ -18780,7 +18780,7 @@

    7.3.3. Generating a dialog response for correctness and displays a suitable message.

    -
    Program 7.3 Generates a dialog with programmer-defined options.
    +
    Programa 7.3 Generates a dialog with programmer-defined options.
    import javax.swing.*;
     
    @@ -18811,13 +18811,13 @@ 

    7.3.3. Generating a dialog - +There are three null values passed into this method. The first one functions like the null used in Programa 7.2, specifying that the default frame should be used. The second specifies that the default icon should be used. In the next section, we’ll show how to specify a custom icon. The last parameter indicates the default button, which will have focus when the dialog is created. If the user hits <enter> instead of clicking, the button with focus is the button that will be pressed. - +
    1We call the showOptionDialog() method to create a dialog with multiple options. In our case, the options are three names of capitals, and only one of them is correct. Figure 7.5 shows the dialog created.
    +
    We call the showOptionDialog() method to create a dialog with multiple options. In our case, the options are three names of capitals, and only one of them is correct. Figura 7.5 shows the dialog created.
    The showOptionDialog() method creates an options dialog, which is the most complicated (but also the most flexible) of all the dialogs. The array of String values provided as the second to last parameter to showOptionDialog() gives the labels for the buttons.
    -There are three null values passed into this method. The first one functions like the null used in Program 7.2, specifying that the default frame should be used. The second specifies that the default icon should be used. In the next section, we’ll show how to specify a custom icon. The last parameter indicates the default button, which will have focus when the dialog is created. If the user hits <enter> instead of clicking, the button with focus is the button that will be pressed.
    2As in Program 7.2, a second dialog is shown with a message dependent on whether the user gives the correct answer.As in Programa 7.2, a second dialog is shown with a message dependent on whether the user gives the correct answer.

    @@ -18825,16 +18825,16 @@

    7.3.3. Generating a dialog
    selectCapitalDialogFigure
    -
    Figure 7.5 A dialog with programmer-defined options generated by Program 7.3.
    +
    Figura 7.5 A dialog with programmer-defined options generated by Programa 7.3.

    @@ -18847,14 +18847,14 @@

    7.3.4. Generating a dialog with a custom icon

    next example illustrates how to do so.

    -
    Example 7.5 Custom icon
    +
    Exemplo 7.5 Custom icon
    -

    Program 7.4 shows how to use +

    Programa 7.4 shows how to use showMessageDialog() to generate a message dialog with a custom icon.

    -
    Program 7.4 Generates a dialog with a custom icon.
    +
    Programa 7.4 Generates a dialog with a custom icon.
    import javax.swing.*;
     
    @@ -18873,7 +18873,7 @@ 

    7.3.4. Generating a dialog with a custom icon

    - +
    1The last parameter creates a new ImageIcon object from the file String ("bat.png" in this case). The resulting dialog appears in Figure 7.6.The last parameter creates a new ImageIcon object from the file String ("bat.png" in this case). The resulting dialog appears in Figura 7.6.
    @@ -18884,7 +18884,7 @@

    7.3.4. Generating a dialog with a custom icon

    customIconDialogFigure
    -
    Figure 7.6 Dialog with a custom icon generated by Program 7.4.
    +
    Figura 7.6 Dialog with a custom icon generated by Programa 7.4.

    Note that the icon shown above will not appear when you run this code @@ -18904,16 +18904,16 @@

    7.3.5. Generating an input dialog

    to show off some of its additional features.

    -
    Example 7.6 Input dialog
    +
    Exemplo 7.6 Input dialog

    We want to write a program that asks a question about basic chemistry. -Program 7.5 shows how to display a question, +Programa 7.5 shows how to display a question, obtain an answer from the user, check for the correctness of the answer, and report back to the user.

    -
    Program 7.5 Generates a dialog to input data as text.
    +
    Programa 7.5 Generates a dialog to input data as text.
    import javax.swing.*;
     
    @@ -18939,7 +18939,7 @@ 

    7.3.5. Generating an input dialog

    - + @@ -18958,7 +18958,7 @@

    7.3.5. Generating an input dialog

    It’s important to note that the user could type any sequence of characters in the dialog box. Try running -Program 7.5 and see what happens when you type +Programa 7.5 and see what happens when you type “two,” instead of the number “2,” into the dialog box and press the “OK” button. The program will generate an exception indicating that the input String cannot be converted to an integer.

    @@ -18967,31 +18967,31 @@

    7.3.5. Generating an input dialog

    inputDialogTextFigure
    -
    Figure 7.7 Dialog to read text input generated by Program 7.5.
    +
    Figura 7.7 Dialog to read text input generated by Programa 7.5.
    -
    Example 7.7 Input dialog with a list
    +
    Exemplo 7.7 Input dialog with a list
    -

    In Example 7.6 the user is required to enter text. To reduce input errors, we can restrict the user to +

    In Exemplo 7.6 the user is required to enter text. To reduce input errors, we can restrict the user to picking from a predefined list. We can create this list by generating an array and supplying it as a parameter to the showInputDialog() method.

    -

    Program 7.6 displays a list of chemical +

    Programa 7.6 displays a list of chemical elements and asks the user to select the heaviest.

    -
    Program 7.6 Generates a dialog to input a choice from a list.
    +
    Programa 7.6 Generates a dialog to input a choice from a list.
    import javax.swing.*;
     
    @@ -19017,8 +19017,8 @@ 

    7.3.5. Generating an input dialog

    1We use the showInputDialog() method to generate the dialog shown in Figure 7.7. This method returns a String named response containing the text entered by the user in the dialog box.We use the showInputDialog() method to generate the dialog shown in Figura 7.7. This method returns a String named response containing the text entered by the user in the dialog box.
    2
    - @@ -19035,7 +19035,7 @@

    7.3.5. Generating an input dialog

    inputDialogListFigure
    -
    Figure 7.8 Dialog to read input from a list generated by Program 7.6.
    +
    Figura 7.8 Dialog to read input from a list generated by Programa 7.6.

    Note that this program will crash if the user clicks the “Cancel” button, @@ -19044,23 +19044,23 @@

    7.3.5. Generating an input dialog

    -
    Example 7.8 Input dialog with a long list
    +
    Exemplo 7.8 Input dialog with a long list
    inputDialogListManyItemsFigure
    -
    Figure 7.9 A dialog requesting user to select one item from a list of 20 data items. Note the use of a scroll down list to display the items.
    +
    Figura 7.9 A dialog requesting user to select one item from a list of 20 data items. Note the use of a scroll down list to display the items.

    When the number of elements in the list supplied to the showInputDialog() is 20 or more, a JList object is automatically used to display the items as shown in -Figure 7.9.

    +Figura 7.9.

    Other than a longer list, the code in this example is virtually -identical to the code in Program 7.6.

    +identical to the code in Programa 7.6.

    @@ -19273,7 +19273,7 @@

    7.7. Exercises

    showMessageDialog() method.

  • -

    In Program 7.2, +

    In Programa 7.2, we could have coded the line checking to see if the user had correctly determined whether the number was odd or even as follows.

    @@ -19301,13 +19301,13 @@

    7.7. Exercises

    1. -

      Modify the program in Example 7.3 such that it +

      Modify the program in Exemplo 7.3 such that it tests the user many times whether a randomly generated integer is odd or even. The program should keep a score indicating the number of correct answers. At the end of the test, display the score using a suitable dialog.

    2. -

      Modify the program in Example 7.3 such that it +

      Modify the program in Exemplo 7.3 such that it displays a dialog that asks the user “Do you wish to continue?” and offers options “Yes” and “No.” The program should exit the loop when the “No” option is selected and display the score using a suitable @@ -19315,26 +19315,26 @@

      7.7. Exercises

    3. Rewrite -Program 7.2 so that the dialog +Programa 7.2 so that the dialog generated offers the “Yes,” “No,” and “Cancel” options to the user. The program should exit with a message dialog saying “Thank You” when the user selects the “Cancel” option.

    4. Modify -Program 7.3 to create and administer a test wherein +Programa 7.3 to create and administer a test wherein the user is asked capitals of 10 countries in a sequence. The program must keep a count of the number of correct answers. Inform the user of the score at the end of the test using a suitable dialog.

    5. -

      Modify Program 7.3 so that the button labeled “Baku” has focus when the program begins.

      +

      Modify Programa 7.3 so that the button labeled “Baku” has focus when the program begins.

    6. Section 8.5 gives a method called shuffle() that can randomize an array representing a deck of cards. Adapt this code and modify -Program 7.3 so that the order of the capitals is +Programa 7.3 so that the order of the capitals is randomized. Note that you will need to record which index contains the correct answer.

    7. @@ -19361,7 +19361,7 @@

      7.7. Exercises

    8. Use a try-catch block and modify -Program 7.5 so that it handles an exception +Programa 7.5 so that it handles an exception generated when the user enters text that cannot be converted to an integer. In the event such an exception is raised, pop up a message dialog box informing the user to try again and type an integer value. @@ -20054,7 +20054,7 @@

      8.3.3. Class variables

      that increases the class variable counter every time it’s called.

    -
    Program 8.1 Keeps track of the number of times the record() method is called.
    +
    Programa 8.1 Keeps track of the number of times the record() method is called.
    public class Bookkeeper {
         public static int counter = 0;
    @@ -20102,7 +20102,7 @@ 

    8.3.3. Class variables

    variable, but with the addition of the final keyword.

    -
    Example 8.1 Gravitational attraction
    +
    Exemplo 8.1 Gravitational attraction

    The following class allows a user to compute the one-dimensional force due to gravity. @@ -20120,7 +20120,7 @@

    8.3.3. Class variables

    constant, 6.673 × 10-11 N⋅m2⋅kg-2.

    -
    Program 8.2 Calculates the attraction due to gravity between two masses.
    +
    Programa 8.2 Calculates the attraction due to gravity between two masses.
    import java.util.Scanner;
     
    @@ -20166,7 +20166,7 @@ 

    8.4. Examples: Defining methods

    int to an int.

    -
    Example 8.2 Euclidean distance
    +
    Exemplo 8.2 Euclidean distance

    The Euclidean distance between two points is the length of a straight @@ -20206,7 +20206,7 @@

    8.4. Examples: Defining methods

    -
    Example 8.3 Palindrome testing
    +
    Exemplo 8.3 Palindrome testing

    A palindrome is a word or phrase (or even a number) that’s the same @@ -20267,12 +20267,12 @@

    8.4. Examples: Defining methods

    -
    Example 8.4 Parsing a number
    +
    Exemplo 8.4 Parsing a number

    When you read in a number using an object of the Scanner class, it @@ -20369,7 +20369,7 @@

    8.4. Examples: Defining methods

    @@ -20681,7 +20681,7 @@

    8.6. Concurrency: Methods

    With multiple threads, even the same method can interfere with itself.

    -
    Example 8.5 LCG without thread safety
    +
    Exemplo 8.5 LCG without thread safety

    A linear congruential generator (LCG) allows you to create a sequence of @@ -20690,7 +20690,7 @@

    8.6. Concurrency: Methods

    previous one, and so on.

    -
    Program 8.3 Implements an LCG similar to one sometimes used in the function rand() used in the C language.
    +
    Programa 8.3 Implements an LCG similar to one sometimes used in the function rand() used in the C language.
    public class UnsafeRandom {
         private static int next = 1;
    @@ -20717,7 +20717,7 @@ 

    8.6. Concurrency: Methods

    possible.

    -
    Program 8.4 Implements the same LCG safely by requiring the caller to supply the previous random number.
    +
    Programa 8.4 Implements the same LCG safely by requiring the caller to supply the previous random number.
    public class SafeRandom {   
         private final static int A = 1103515245;
    @@ -20733,7 +20733,7 @@ 

    8.6. Concurrency: Methods

    -
    Example 8.6 Unpredictable methods
    +
    Exemplo 8.6 Unpredictable methods

    By forcing each thread to carry its own state, we fixed the previous @@ -20743,7 +20743,7 @@

    8.6. Concurrency: Methods

    following program.

    -
    Program 8.5 The print() method always prints "Even" when run with a single thread but can sometimes print "Odd" if called repeatedly with multiple threads.
    +
    Programa 8.5 The print() method always prints "Even" when run with a single thread but can sometimes print "Odd" if called repeatedly with multiple threads.
    public class AlwaysEven {
         private static int value = 1;
    @@ -20968,13 +20968,13 @@ 

    8.7. Exercises

  • Write a method that tests palindromes like -the method from Example 8.3 but also ignores +the method from Exemplo 8.3 but also ignores punctuation and spaces. Thus, "A man, a plan, a canal: Panama" should be counted as a palindrome by this new method.

  • Add to the parseDouble() method from -Example 8.4 so that it can also handle numbers in standard Java +Exemplo 8.4 so that it can also handle numbers in standard Java scientific notation, such as 7.239e-14. Note that the e can be uppercase or lowercase, and the exponent can begin with a minus sign (-), a plus sign (+), or neither.

    @@ -21274,7 +21274,7 @@

    9.2.1. Objects

    class
    -
    Figure 9.1 Example of a class serving as a template for an object.
    +
    Figura 9.1 Example of a class serving as a template for an object.

    This idea of a class as a template is key because it means that an @@ -21387,7 +21387,7 @@

    9.3.1. Fields

    actually want to use an object, we’ll have to create one.

    -
    Program 9.1 Class encapsulating the attributes of a human being.
    +
    Programa 9.1 Class encapsulating the attributes of a human being.
    public class Human {    
         private String name;
    @@ -21451,7 +21451,7 @@ 

    9.3.1. Fields

    staticvalue
    -
    Figure 9.2 Class variables (static fields) are stored with the class, not with individual objects.
    +
    Figura 9.2 Class variables (static fields) are stored with the class, not with individual objects.
    @@ -21817,7 +21817,7 @@

    9.3.4. Access modifiers

    objects can be used to make a roster of students.

    -
    Example 9.1 Student roster
    +
    Exemplo 9.1 Student roster

    We’re going to create a Student class so that we can store objects @@ -22026,7 +22026,7 @@

    9.4.1. Static nested classes

    nested
    -
    Figure 9.3 A static nested class object is allowed to access data from outer class objects even though there’s no direct relationship between them.
    +
    Figura 9.3 A static nested class object is allowed to access data from outer class objects even though there’s no direct relationship between them.

    Static nested classes can be used when the class you need is only useful @@ -22055,7 +22055,7 @@

    9.4.1. Static nested classes

    classes using the sames access rules for fields and methods.

    -
    Example 9.2 Static nested class for testing
    +
    Exemplo 9.2 Static nested class for testing

    One application for static nested classes is testing. You can write code @@ -22180,7 +22180,7 @@

    9.4.2. Inner classes

    inner
    -
    Figure 9.4 An inner class object is always associated with a specific outer class object.
    +
    Figura 9.4 An inner class object is always associated with a specific outer class object.

    Another issue with inner classes (as opposed to static nested classes) @@ -22198,7 +22198,7 @@

    9.4.2. Inner classes

    they’re created and used, we’ll discuss them in Section 10.4

    -
    Example 9.3 Inner class objects as iterators
    +
    Exemplo 9.3 Inner class objects as iterators

    If you create a data structure for other programmers to use, a useful @@ -22300,7 +22300,7 @@

    9.5. Solution: Nested expressions

    stack operations with methods of the same names.

    -
    Program 9.2 Simple stack class to hold symbols from an input expression.
    +
    Programa 9.2 Simple stack class to hold symbols from an input expression.
    public class SymbolStack {
         private char[] symbols;
    @@ -22468,8 +22468,8 @@ 

    9.5. Solution: Nested expressions

    @@ -22498,7 +22498,7 @@

    9.6. Concurrency: Objects

    has, losing one every time it becomes curious.

    -
    Example 9.4 Thread safety
    +
    Exemplo 9.4 Thread safety

    If the relationship between curiosity and mortality is the only feature @@ -22513,7 +22513,7 @@

    9.6. Concurrency: Objects

    pause in executing the useCuriosity() method.

    -
    Program 9.3 Records the number of lives a cat has left. Each Cat object starts with 9, but loses one each time it uses its curiosity. If no more lives remain, an error message is output.
    +
    Programa 9.3 Records the number of lives a cat has left. Each Cat object starts with 9, but loses one each time it uses its curiosity. If no more lives remain, an error message is output.
    public class Cat {
         private int lives = 9;
    @@ -22841,7 +22841,7 @@ 

    10.1. Problem: Sort it out

    Person and Cheese objects is simply their calendar age.

    -

    As we discussed in Example 6.2, sorting is one of +

    As we discussed in Exemplo 6.2, sorting is one of the most fundamental tools for computer scientists. In that example, we introduced selection sort. Here we’re going to use another sort called bubble sort. We introduce bubble sort to expose you to @@ -23287,7 +23287,7 @@

    10.3.2. Interfaces and static

    them in many cases.

    -
    Example 10.1 Supermarket pricing
    +
    Exemplo 10.1 Supermarket pricing

    Interface names often include the suffix -able, for example, @@ -23434,7 +23434,7 @@

    10.4.1. Local classes

    ellipse
    -
    Figure 10.1 Area of an ellipse.
    +
    Figura 10.1 Area of an ellipse.
    @@ -23527,7 +23527,7 @@

    10.4.1. Local classes

    Even though the Ellipse class had the getArea() method before, the compiler wouldn’t have allowed us to store Ellipse references in an AreaGettable array until we marked the Ellipse class as implementing -AreaGettable. As in Example 10.1, we used +AreaGettable. As in Exemplo 10.1, we used an array with an interface type.

    @@ -23615,7 +23615,7 @@

    10.4.2. Anonymous classes

    10.5. Solution: Sort it out

    It’s not difficult to move from totaling the value of items as we did -in Example 10.1 to sorting them. Refer to the +in Exemplo 10.1 to sorting them. Refer to the following class diagram as we explain our solution to the sorting problem posed at the beginning of the chapter. Dotted lines are used to show the “implements” relationship.

    @@ -23624,7 +23624,7 @@

    10.5. Solution: Sort it out

    ageandweight
    -
    Figure 10.2 Sorting relationships.
    +
    Figura 10.2 Sorting relationships.

    We’ll start with the definitions of the two interfaces we’ll use to @@ -23813,7 +23813,7 @@

    10.6. Concurrency: Interfaces

    the main() method, some method needs to be marked as a starting place for additional threads. For more information about using the Runnable interface, refer to -Section 13.4.5.

    +[The Runnable interface].

    The second connection between interfaces and concurrency is more @@ -24054,7 +24054,7 @@

    10.7. Exercises

    the array you took the data from as well as the index of the result array. Be careful not to go beyond the end of the arrays which are being merged. An implementation of merging can be found -in Example 19.8.

    +in Exemplo 19.8.

  • @@ -24066,7 +24066,7 @@

    10.7. Exercises

    1. Once you have implemented the sort in parallel from -Exercise 10.14, time it against the sequential +Exercício 10.14, time it against the sequential version. Try two, four, and eight different threads. Be sure to create one random array and use copies of the original array for both the parallel and sequential versions. Be careful not to sort an array that’s already @@ -24162,7 +24162,7 @@

      11.1. Problem: Boolean circuits

      circuit
      -
      Figure 11.1 Final circuit diagram showing the six components.
      +
      Figura 11.1 Final circuit diagram showing the six components.

      We’re only interested in the value of any OUTPUT gates. Thus, the @@ -24198,7 +24198,7 @@

      11.1. Problem: Boolean circuits

      gates
      -
      Figure 11.2 Recommended inheritance hierarchy.
      +
      Figura 11.2 Recommended inheritance hierarchy.

      As you can see, every class inherits from the Gate class. If your @@ -24212,7 +24212,7 @@

      11.1. Problem: Boolean circuits

      @@ -24301,7 +24301,7 @@

      11.2.3. Code reuse

      @@ -24654,7 +24654,7 @@

      11.3.4. Overriding methods and hi @@ -24719,7 +24719,7 @@

      11.3.4. Overriding methods and hi @@ -24817,16 +24817,16 @@

      11.4. Examples: Problem solv of polygons.

      -
      Example 11.1 Graduate student roster
      +
      Exemplo 11.1 Graduate student roster
      -

      The Student class we created in Example 9.1 is useful +

      The Student class we created in Exemplo 9.1 is useful but works only for undergraduate students. With only a few additions, we can make it suitable for graduate students as well. First, let’s take another look at the Student class.

      -
      Program 11.1 Basic student class, designed for undergraduates.
      +
      Programa 11.1 Basic student class, designed for undergraduates.
      public class Student {
           public static final String[] YEARS = {"Freshman", "Sophomore", "Junior", "Senior"};
      @@ -24867,7 +24867,7 @@ 

      11.4. Examples: Problem solv appropriate data. We use 4 as the year value for graduate students.

      -
      Program 11.2 Class extending Student to add graduate student capabilities.
      +
      Programa 11.2 Class extending Student to add graduate student capabilities.
      public class GraduateStudent extends Student {
           private String topic; (1)
      @@ -24918,12 +24918,12 @@ 

      11.4. Examples: Problem solv
      -
      Example 11.2 Polygons
      +
      Exemplo 11.2 Polygons

      Let’s examine a class hierarchy used to create several different @@ -25139,7 +25139,7 @@

      11.4. Examples: Problem solv @@ -25316,7 +25316,7 @@

      11.5. Solution: Boolean circuits

      @@ -25434,7 +25434,7 @@

      11.6. Concurrency: Inheritance

      your own customized threads of execution is an alternative to implementing the Runnable interface mentioned in Section 10.6 and is discussed in greater detail in -Section 13.4.5.

      +[The Runnable interface].

      The second interaction between inheritance and concurrency is again very @@ -25638,7 +25638,7 @@

      11.7. Exercises

      -

      As mentioned in Example 8.1, the gravitational constant G = 6.673 × 10-11 N⋅m2⋅kg-2. +

      As mentioned in Exemplo 8.1, the gravitational constant G = 6.673 × 10-11 N⋅m2⋅kg-2. Also, |rab| is the distance between the centers of objects a and b. Finally, the unit vector between the centers of the two objects is given by the equation below.

      @@ -25883,7 +25883,7 @@

      12.2.1. Error codes

      @@ -26073,7 +26073,7 @@

      12.3.2. Handling exceptions

      @@ -26118,8 +26118,8 @@

      12.3.3. Catch or specify

      @@ -26131,7 +26131,7 @@

      12.3.3. Catch or specify

      @@ -26147,8 +26147,8 @@

      12.3.3. Catch or specify

      @@ -26225,9 +26225,9 @@

      12.3.4. The finally keyword

      @@ -26279,9 +26279,9 @@

      12.3.5. Customized exceptions

      @@ -26293,7 +26293,7 @@

      12.3.5. Customized exceptions

      and end with a custom exception used with the Color class.

      -
      Example 12.1 Calculator with division by zero
      +
      Exemplo 12.1 Calculator with division by zero

      Here we implement a quick calculator that reads input from the user @@ -26389,7 +26389,7 @@

      12.3.5. Customized exceptions

      -
      Example 12.2 Array bounds
      +
      Exemplo 12.2 Array bounds

      Exceptions provide a lot of power. If we want, we can use the @@ -26441,12 +26441,12 @@

      12.3.5. Customized exceptions

      -
      Example 12.3 Color ranges
      +
      Exemplo 12.3 Color ranges

      The Color class provided by Java allows us to represent a color as a @@ -26795,7 +26795,7 @@

      12.5. Concurrency: Exceptions

      throwing the exception dies.

      -
      Example 12.4 Multiple threads with exceptions
      +
      Exemplo 12.4 Multiple threads with exceptions

      In a program with a single thread, an exception thrown by the main() @@ -26805,7 +26805,7 @@

      12.5. Concurrency: Exceptions

      will run to completion before the JVM shuts down.

      -
      Program 12.1 Spawns 10 threads. 9 out of 10 spawned threads as well as the main thread throw an exception and die. The remaining thread outputs the sum of the sines of 1 through 1,000,000.
      +
      Programa 12.1 Spawns 10 threads. 9 out of 10 spawned threads as well as the main thread throw an exception and die. The remaining thread outputs the sum of the sines of 1 through 1,000,000.
      public class CrazyThread extends Thread {
           private int value;
      @@ -27016,7 +27016,7 @@ 

      12.6. Exercises

    2. Refer to -Exercise 11.14 and add to the basic mechanics of the simulation by designing two custom +Exercício 11.14 and add to the basic mechanics of the simulation by designing two custom exceptions, CollisionException and LightSpeedException. These exceptions should be thrown, respectively, if two bodies collide or if the total magnitude of a body’s velocity exceeds the speed of light.

      @@ -27100,9 +27100,6 @@

      12.6. Exercises

    -
    -

    :lang:pt-BR

    -
    @@ -27191,7 +27188,7 @@

    13.3. Conceitos: Dividindo para co @@ -27229,15 +27226,15 @@

    13.3.1. Decomposição de tarefas

    Os dois exemplos a seguir mostram ilustrações simples do processo de divisão de uma tarefa em subtarefas menores no contexto da programação multicore.

    -
    -
    Example 13.1 Tarefas de videogame
    +
    +
    Exemplo 13.1 Tarefas de videogame

    Considere um videogame simples que consiste nas seguintes tarefas

    @@ -27265,18 +27262,18 @@

    13.3.1. Decomposição de tarefas

    video game tasks
    -
    Figure 13.1 Execução de tarefas em um vídeogame. (a) Execução sequencial em um núcleo. (b) Execução concorrente em dois núcleos. As setas indicam o fluxo de execução e de transferência de dados.
    +
    Figura 13.1 Execução de tarefas em um vídeogame. (a) Execução sequencial em um núcleo. (b) Execução concorrente em dois núcleos. As setas indicam o fluxo de execução e de transferência de dados.

    Suponha que as tarefas B e D sejam independentes e possam ser executadas simultaneamente se houver dois núcleos disponíveis. A tarefa D atualiza continuamente a tela com os dados antigos até que a tarefa C atualize as informações.

    -

    Figure 13.1(a) e (b) mostram como as tarefas desse videogame podem ser sequenciadas, respectivamente, em um único núcleo ou em dois núcleos. Todas as tarefas são executadas sequencialmente em um processador de núcleo único. Em um processador de núcleo duplo, as tarefas B e C podem ser executadas em um núcleo enquanto a tarefa D é executada simultaneamente em outro. Observe na figura que a tarefa C envia a pontuação e qualquer outros dados para a tarefa D, que atualiza continuamente a tela. Ter dois núcleos pode permitir uma atualização mais rápida da tela, pois o processador não precisa esperar que as tarefas B ou C sejam concluídas.

    +

    Figura 13.1(a) e (b) mostram como as tarefas desse videogame podem ser sequenciadas, respectivamente, em um único núcleo ou em dois núcleos. Todas as tarefas são executadas sequencialmente em um processador de núcleo único. Em um processador de núcleo duplo, as tarefas B e C podem ser executadas em um núcleo enquanto a tarefa D é executada simultaneamente em outro. Observe na figura que a tarefa C envia a pontuação e qualquer outros dados para a tarefa D, que atualiza continuamente a tela. Ter dois núcleos pode permitir uma atualização mais rápida da tela, pois o processador não precisa esperar que as tarefas B ou C sejam concluídas.

    -
    Example 13.2 Tarefas de expressão matemática
    +
    Exemplo 13.2 Tarefas de expressão matemática

    Suponha que precisemos avaliar a expressão matemática 2Kate-⁠at² com os parâmetros a e K em um determinado valor de t. Podemos dividir a expressão em dois termos: 2Kat e e-⁠at². Cada um desses termos pode ser atribuído a uma tarefa diferente para avaliação. Em um processador de dois núcleos, essas duas tarefas podem ser executadas em núcleos separados e os resultados de cada uma delas podem ser combinados para encontrar o valor da expressão para a tarefa principal.

    @@ -27285,18 +27282,18 @@

    13.3.1. Decomposição de tarefas

    mathematical expression evaluation
    -
    Figure 13.2 Avaliação de uma expressão matemática (a) sequencialmente em um único núcleo e (b) simultaneamente em dois núcleos. As setas mostram o fluxo de execução e a transferência de dados. A fonte em destaque indica a operação que está sendo executada.
    +
    Figura 13.2 Avaliação de uma expressão matemática (a) sequencialmente em um único núcleo e (b) simultaneamente em dois núcleos. As setas mostram o fluxo de execução e a transferência de dados. A fonte em destaque indica a operação que está sendo executada.
    -

    Figure 13.2 mostra como essa expressão pode ser avaliada em processadores de um núcleo e de dois núcleos. Às vezes, o uso de vários núcleos para avaliar uma expressão como essa levará menos tempo do que um único núcleo. No entanto, não há garantia de que o uso de vários núcleos sempre será mais rápido, pois as tarefas levam tempo para serem configuradas e para se comunicarem entre si.

    +

    Figura 13.2 mostra como essa expressão pode ser avaliada em processadores de um núcleo e de dois núcleos. Às vezes, o uso de vários núcleos para avaliar uma expressão como essa levará menos tempo do que um único núcleo. No entanto, não há garantia de que o uso de vários núcleos sempre será mais rápido, pois as tarefas levam tempo para serem configuradas e para se comunicarem entre si.

    @@ -27322,7 +27319,7 @@

    13.3.2. Decomposição de domínio

    Ilustramos a estratégia de decomposição de domínio nos dois exemplos a seguir.

    -
    Example 13.3 Visualização da soma de matrizes
    +
    Exemplo 13.3 Visualização da soma de matrizes

    Suponha que queiramos aplicar a função f a cada elemento @@ -27350,19 +27347,19 @@

    13.3.2. Decomposição de domínio

    arrayDecomposition
    -
    Figure 13.3 Calculando a soma de uma função de cada elemento de uma matriz.
    +
    Figura 13.3 Calculando a soma de uma função de cada elemento de uma matriz.

    Depois que S1 e S2 tiverem sido computados, um dos núcleos pode somar esses dois números para obter S. -Essa estratégia é ilustrada em Figure 13.3. +Essa estratégia é ilustrada em Figura 13.3. Depois que os dois núcleos tiverem concluído seu trabalho em cada metade da matriz, as somas individuais são então somadas para produzir o resultado final.

    -
    Example 13.4 Visualização da multiplicação de matrizes
    +
    Exemplo 13.4 Visualização da multiplicação de matrizes

    A necessidade de multiplicar matrizes surge em muitas aplicações matemáticas, científicas e de engenharia. Suponha que nos peçam para escrever um programa para @@ -27377,12 +27374,12 @@

    13.3.2. Decomposição de domínio

    matrixDecomposition
    -
    Figure 13.4 Decomposição de dados para multiplicar duas matrizes 4 × 4. Os dois núcleos executam as mesmas tarefas de multiplicação, mas em dados diferentes da matriz A.Os dois núcleos calculam as duas linhas superiores e as duas linhas inferiores de C, respectivamente.
    +
    Figura 13.4 Decomposição de dados para multiplicar duas matrizes 4 × 4. Os dois núcleos executam as mesmas tarefas de multiplicação, mas em dados diferentes da matriz A.Os dois núcleos calculam as duas linhas superiores e as duas linhas inferiores de C, respectivamente.

    Neste problema, a tarefa é multiplicar as matrizes A e B. Por meio da decomposição de domínio, podemos replicar essa -tarefa em cada núcleo. Conforme mostrado na Figure 13.4, +tarefa em cada núcleo. Conforme mostrado na Figura 13.4, cada núcleo calcula apenas uma parte de C. Por exemplo, se A e B forem 4 × 4, podemos pedir a um núcleo que calcule o produto das duas primeiras linhas de A com todas as quatro colunas de B para @@ -27417,19 +27414,19 @@

    13.3.3. Tarefas e threads

    de execução. Lembre-se dos exemplos anteriores de programação concorrente neste capítulo.

    -

    Considere a possibilidade de dividir as tarefas em [videoGameTasksExample] em +

    Considere a possibilidade de dividir as tarefas em Exemplo 13.1 em duas threads. As tarefas B e C podem ser agrupadas na thread 1, e a tarefa D pode ser empacotada na thread 2.Essa divisão é mostrada em -Figure 13.5(a).

    +Figura 13.5(a).

    -

    As tarefas para avaliar diferentes subexpressões em Example 13.2 também podem ser divididas em duas threads, conforme mostrado em Figure 13.5 (b). Em muitos problemas, há várias maneiras razoáveis de dividir um conjunto de subtarefas em threads.

    +

    As tarefas para avaliar diferentes subexpressões em Exemplo 13.2 também podem ser divididas em duas threads, conforme mostrado em Figura 13.5 (b). Em muitos problemas, há várias maneiras razoáveis de dividir um conjunto de subtarefas em threads.

    task thread packaging
    -
    Figure 13.5 (a) Tarefas em um videogame mostradas agrupadas em duas threads. (b) Tarefas para avaliar uma expressão matemática mostrada empacotada em duas threads. Cada thread pode ou não ser executado no mesmo núcleo que o outro.
    +
    Figura 13.5 (a) Tarefas em um videogame mostradas agrupadas em duas threads. (b) Tarefas para avaliar uma expressão matemática mostrada empacotada em duas threads. Cada thread pode ou não ser executado no mesmo núcleo que o outro.

    Observe que essas figuras são exatamente iguais às figuras anteriores, exceto @@ -27443,13 +27440,13 @@

    13.3.3. Tarefas e threads

    main, pois ela contém o método main().

    -

    Example 13.3 e Example 13.4 usam várias tarefas idênticas, -mas essas tarefas operam em dados diferentes. Em Example 13.3, +

    Exemplo 13.3 e Exemplo 13.4 usam várias tarefas idênticas, +mas essas tarefas operam em dados diferentes. Em Exemplo 13.3, as duas tarefas podem ser atribuídas a duas threads que operam em diferentes partes da matriz de entrada. A tarefa de somar os resultados das duas threads pode ser uma thread separada ou uma subtarefa incluída em uma das outras threads. Em -Example 13.4, as duas tarefas podem +Exemplo 13.4, as duas tarefas podem novamente ser atribuídas a duas threads distintas que operam em diferentes partes diferentes da matriz de entrada A para gerar as partes correspondentes partes correspondentes da matriz de saída C.

    @@ -27514,21 +27511,15 @@

    13.4.1. A classe Thread

    suas subclasses. Esse método é o ponto de partida para a thread de execução associada a uma instância da classe. A maioria dos aplicativos Java começa com uma única thread principal que é iniciado em um método main(). As threads adicionais devem começar em algum lugar, e esse lugar é o método run(). Um aplicativo Java continuará a ser executado enquanto houver pelo menos uma thread ativa. O exemplo a seguir mostra duas threads, -cada uma avaliando uma subexpressão separada, como em Figure 13.5(b).

    +cada uma avaliando uma subexpressão separada, como em Figura 13.5(b).

    -
    Example 13.5 Exemplos de Threads
    +
    Exemplo 13.5 Exemplos de Threads
    -

    Vamos criar as classes Thread1 e Thread2. As threads de execução criadas por instâncias -destas classes calculam, respetivamente, as duas subexpressões da Figure 13.5(b) e -guardam os valores calculados.

    -
    -
    -

    We’ll create Thread1 and Thread2 classes. The threads of execution -created by instances of these classes compute, respectively, the two -subexpressions in Figure 13.5(b) and save the -computed values.

    +

    Vamos criar as classes Thread1 e Thread2. As threads de execução criadas por +instâncias destas classes calculam, respetivamente, as duas subexpressões da +Figura 13.5(b) e guardam os valores calculados.

    @@ -27560,19 +27551,19 @@

    13.4.1. A classe Thread

    -

    The run() method in each thread above computes a subexpression and -saves its value. We show how these threads can be executed to solve the -math expression problem in Example 13.6.

    +

    O método run() em cada thread acima calcula uma subexpressão e salva seu +valor. Mostramos como essas threads podem ser executados para resolver o problema +da expressão matemática em Exemplo 13.6.

    -

    13.4.2. Creating a thread object

    +

    13.4.2. Criando um objeto thread

    -

    Creating an object from a subclass of Thread is the same as creating -any other object in Java. For example, we can instantiate the Thread1 -class above to create an object called thread1.

    +

    Criar um objeto a partir de uma subclasse Thread é o mesmo que criar +qualquer outro objeto em Java. Por exemplo, podemos instanciar a classe Thread1 +acima para criar um objeto chamado thread1.

    @@ -27580,19 +27571,19 @@

    13.4.2. Creating a thread object

    -

    Using the new keyword to invoke the constructor creates a Thread1 -object, but it doesn’t start executing it as a new thread. As with all -other classes, the constructor initializes the values inside of the new -object. A subclass of Thread can have many different constructors with -whatever parameters its designer thinks appropriate.

    +

    O uso da palavra-chave new para invocar o construtor cria um objeto Thread1, +mas não começa a executá-lo como uma nova thread. Como em todas as +outras classes, o construtor inicializa os valores dentro do novo objeto +objeto. Uma subclasse de Thread pode ter muitos construtores diferentes com +qualquer parâmetros que seu projetista considere apropriados.

    -

    13.4.3. Starting a thread

    +

    13.4.3. Iniciando uma thread

    -

    To start the thread object executing, its start() method must be -called. For example, the thread1 object created above can be started -as follows.

    +

    Para iniciar a execução do objeto thread, seu método start() deve ser +chamado. Por exemplo, o objeto thread1 criado acima pode ser iniciado +da seguinte forma.

    @@ -27600,19 +27591,19 @@

    13.4.3. Starting a thread

    -

    Once started, a thread executes independently. Calling the start() -method automatically calls the object’s run() method behind the -scenes. When a thread needs to share data with another thread, it -might have to wait.

    +

    Uma vez iniciado, uma thread é executada de forma independente. A chamada do método start() +chama automaticamente o método run() do objeto nos bastidores. +Quando uma thread precisa compartilhar dados com outra thread, ela +pode ter que esperar.

    -

    13.4.4. Waiting for a thread

    +

    13.4.4. Aguardando por uma thread

    -

    Often some thread, main or otherwise, needs to wait for another thread -before proceeding further with its execution. The join() method is -used to wait for a thread to finish executing. For example, whichever -thread executes the following code will wait for thread1 to complete.

    +

    Muitas vezes, alguma thread, principal ou não, precisa esperar por outra thread +antes de prosseguir com sua execução. O método join() é usado para esperar +que uma thread termine a execução. Por exemplo, qualquer thread que executar o +código a seguir aguardará a conclusão da thread1.

    @@ -27620,31 +27611,31 @@

    13.4.4. Waiting for a thread

    -

    Calling join() is a blocking call, meaning that the code calling -this method will wait until it returns. Since it can throw a a checked -InterruptedException while the code’s waiting, the join() method -is generally used within a try-catch block. We can add a -try-catch block to the thread1 example so that we can recover from -being interrupted while waiting for thread1 to finish.

    +

    A chamada join() é uma chamada bloqueante, o que significa que o código que chama +esse método aguardará até que ele retorne. Como ele pode lançar uma +InterruptedException verificada enquanto o código estiver aguardando, o método join() +é geralmente usado em um bloco try-catch. Podemos adicionar um bloco try-catch +ao exemplo thread1 para que possamos nos recuperar de +sermos interrompidos enquanto aguardamos a conclusão do thread1.

    try {
    -	System.out.println("Waiting for thread 1...");
    +	System.out.println("Aguardando pela thread 1...");
     	thread1.join();
    -	System.out.println("Thread 1 finished!");
    +	System.out.println("Thread 1 finalizada!");
     }
     catch (InterruptedException e) {
    -	System.out.println("Thread 1 didn't finish!");
    +	System.out.println("Thread 1 não acabou!");
     }
    -

    Note that the InterruptedException is thrown because the main thread -was interrupted while waiting for thread1 to finish. If the join() -call returns, then thread1 must have finished, and we inform the user. -If an InterruptedException is thrown, some outside thread must have -interrupted the main thread, forcing it to stop waiting for thread1.

    +

    Observe que a InterruptedException é lançada porque a thread principal +foi interrompida enquanto aguardava a conclusão da thread1. Se a chamada join() +retornar, então thread1 deve ter terminado e informaremos o usuário. +Se uma InterruptedException for lançada, alguma thread externa deve ter +interrompido a thread principal, forçando-a a parar de esperar pela thread1.

    In earlier versions of Java, there was a stop() method which would @@ -27655,22 +27646,21 @@

    13.4.4. Waiting for a thread

    -
    Example 13.6 Math expression threads
    +
    Exemplo 13.6 Cálculos matemáticos com threads
    -

    Now that we have the syntax to start threads and wait for them to -finish, we can use the threads defined in Example 13.5 with a -main thread to make our first complete concurrent -program. The main thread in class MathExpression creates and starts -the worker threads thread1 and thread2 and waits for their -completion. When the two threads complete their execution, we can ask -each for its computed value. The main thread then prints the product of -these values, which is the result of the expression we want to evaluate.

    +

    Agora que temos a sintaxe para iniciar threads e esperar que eles terminem, podemos +usar as threads definidos em Exemplo 13.5 com uma thread principal +para criar nosso primeiro programa concorrente completo. A thread principal na +classe MathExpression cria e inicia as threads de trabalho thread1 e thread2 +e aguarda sua conclusão. Quando as duas threads concluem sua execução, podemos +solicitar a cada uma delas o valor calculado. A thread principal imprime o +produto desses valores, que é o resultado da expressão que queremos avaliar.

    @@ -27695,55 +27685,50 @@

    13.4.4. Waiting for a thread

    -

    We want to make it absolutely clear when threads are created, start -executing, and finish. These details are crucial for the finer points of -concurrent Java programming. In Figure 13.5, it -appears as if execution of the concurrent math expression evaluation -begins with Thread 1 which spawns Thread 2. Although that figure -explains the basics of task decomposition well, the details are messier -for real Java code.

    +

    Queremos deixar absolutamente claro quando os threads são criados, começam +a execução e terminam. Esses detalhes são cruciais para os pontos mais finos da +programação Java simultânea. Na Figura 13.5, parece que a execução da avaliação da expressão matemática +começa com a Thread 1, que gera a Thread 2. Embora essa figura +explique bem os conceitos básicos da decomposição de tarefas, os detalhes são mais confusos para o código Java real.

    -

    In the code above, execution starts with the main() method in -MathExpression. It creates Thread1 and Thread2 objects and waits -for them to finish. Then, it reads the values from the objects after -they’ve stopped executing. We could have put the main() method in -the Thread1 class, omitting the MathExpression class entirely. Doing -so would make the execution match Figure 13.5 -more closely, but it would make the two Thread subclasses less -symmetrical: The main thread and thread1 would both independently -execute code inside the Thread1 class while only thread2 would -execute code inside the Thread2 class.

    +

    No código acima, a execução começa com o método main() em +MathExpression. Ele cria os objetos Thread1 e Thread2 e aguarda +que eles terminem. Em seguida, ele lê os valores dos objetos depois que +eles pararam de ser executados. Poderíamos ter colocado o método main() na classe Thread1, omitindo totalmente a classe MathExpression. Desta forma isso faria com que a execução correspondesse mais de perto à Figura 13.5 +mais próxima, mas tornaria as duas subclasses Thread menos +simétricas: a thread principal e a thread1 executariam independentemente o código dentro da Thread1. +executariam independentemente o código dentro da classe Thread1, enquanto somente thread2 executaria +executaria código dentro da classe Thread2.

    thread lifecycle
    -
    Figure 13.6 Creation, starting, and joining of threads in MathExpression, Thread1, and Thread2.
    +
    Figura 13.6 Criando, iniciando, e mesclando as threads em MathExpression, Thread1, and Thread2.
    -

    Figure 13.6 shows the execution of thread1 and -thread2 and the main thread. Note that the JVM implicitly creates and starts -the main thread which explicitly creates and starts thread1 and thread2. -Even after the threads associated with thread1 and thread2 have stopped running, -the objects associated with them continue to exist. Their methods and fields can still be -accessed.

    +

    Figura 13.6 mostra a execução de thread1 e +thread2 e a thread principal. Observe que a JVM cria e inicia implicitamente +o thread principal, que cria e inicia explicitamente a thread1 e a thread2. +Mesmo depois que as threads associados a thread1 e thread2 pararem de ser executados, +os objetos associados a eles continuam a existir. Seus métodos e campos ainda podem ser acessados.

    -

    13.4.5. The Runnable interface

    +

    13.4.5. A interface Runnable

    -

    Although it’s possible to create Java threads by inheriting from the -Thread class directly, the Java API allows the programmer to use an -interface instead.

    +

    Embora seja possível criar threads em Java herdando diretamente da classe +Thread diretamente, a API Java permite que o programador use uma +interface em vez disso.

    -

    As an example, the Summer class takes an array of int values and -sums them up within a given range. If multiple instances of this class -are executed as separate threads, each one can sum up different parts of -an array.

    +

    Como exemplo, a classe Summer pega uma matriz de valores int e os soma dentro +de um determinado intervalo. Se várias instâncias dessa classe +forem executadas como threads separadas, cada uma delas poderá somar diferentes partes de +uma matriz.

    @@ -27769,18 +27754,16 @@

    13.4.5. The Runnable interface

    -

    This class is very similar to one that inherits from Thread. Imagine -for a moment that the code following Summer is extends Thread -instead of implements Runnable. The key thing a class derived from -Thread needs is an overridden run() method. Since only the run() -method is important, the designers of Java provided a way to create a -thread using the Runnable interface. To implement this interface, only -a public void run() method is required.

    +

    Essa classe é muito semelhante a uma classe que herda de Thread. Imagine +por um momento que o código que segue Summer é extends Thread +em vez de implements Runnable. A principal coisa que uma classe derivada de +Thread precisa é de um método run() sobrescrito. Como somente o método run() +é importante, os projetistas do Java forneceram uma maneira de criar uma +thread usando a interface Runnable. Para implementar essa interface, é necessário apenas +um método public void run().

    -

    When creating a new thread, there are some differences in syntax between -the two styles. The familiar way of creating and running a thread from a -Thread subclass is as follows.

    +

    Ao criar uma nova thread, há algumas diferenças de sintaxe entre os dois estilos. A maneira conhecida de criar e executar um thread a partir de uma subclasse Thread é a seguinte.

    @@ -27789,10 +27772,7 @@

    13.4.5. The Runnable interface

    -

    Since Summer doesn’t inherit from Thread, it doesn’t have a -start() method, and this code won’t compile. When a class only -implements Runnable, it’s still necessary to create a Thread object -and call its start() method. Thus, an extra step is needed.

    +

    Como o Summer não herda de Thread, ele não tem um método start(), e esse código não será compilado. Quando uma classe apenas implementa Runnable, ainda é necessário criar um objeto Thread e chamar seu método start(). Portanto, é necessária uma etapa extra.

    @@ -27802,28 +27782,25 @@

    13.4.5. The Runnable interface

    -

    This alternate way of implementing the Runnable interface seems more -cumbersome than inheriting directly from Thread, since you have to -instantiate a separate Thread object. However, most developers prefer -to design classes that implement Runnable instead of inheriting from -Thread. Why? Java only allows for single inheritance. If your class -implements Runnable, it’s free to inherit from another parent class -with features you might want.

    +

    Essa forma alternativa de implementar a interface Runnable parece mais incômoda do que herdar diretamente da Thread, já que é necessário +instanciar um objeto Thread separado. Entretanto, a maioria dos desenvolvedores prefere projetar classes que implementem Runnable em vez de herdar de +Thread. Por quê? O Java só permite herança única. Se sua classe +implementar Runnable, ela estará livre para herdar de outra super classe +com os recursos que você desejar.

    -
    Example 13.7 Array of threads
    +
    Exemplo 13.7 Conjunto de threads
    -

    In domain decomposition, we often need to create multiple threads, all -from the same class. As an example, consider the following thread -declaration.

    +

    Na decomposição de domínios, muitas vezes precisamos criar várias threads, todas +a partir da mesma classe. Como exemplo, considere a seguinte declaração de thread.

    @@ -27839,8 +27816,8 @@

    13.4.5. The Runnable interface

    -

    Now, suppose we want to create 10 thread objects of type -NumberedThread, start them, and then wait for them to complete.

    +

    Agora, suponha que desejemos criar 10 objetos de thread do tipo +NumberedThread, então iniciá-los e por fim esperar que sejam concluídos.

    @@ -27862,74 +27839,66 @@

    13.4.5. The Runnable interface

    - + - + - + - +
    1We pass an array of four String values to the showInputDialog() method. Note that the last parameter to this method is null indicating that no specific item on the list should be selected by default. (In this case, the first item in the list is initially selected.) The generated dialog is shown in Figure 7.8. The four elements are contained in a drop-down list.
    -Unlike Example 7.6, the return value from showInputDialog() is now of type Object, not of type String. The type of the list required by the method is Object array. You’re allowed to pass a String array to a method that wants an Object array due to inheritance, which is further discussed in +
    We pass an array of four String values to the showInputDialog() method. Note that the last parameter to this method is null indicating that no specific item on the list should be selected by default. (In this case, the first item in the list is initially selected.) The generated dialog is shown in Figura 7.8. The four elements are contained in a drop-down list.
    +Unlike Exemplo 7.6, the return value from showInputDialog() is now of type Object, not of type String. The type of the list required by the method is Object array. You’re allowed to pass a String array to a method that wants an Object array due to inheritance, which is further discussed in Chapter 11 and Chapter 17. The return value is the specific object from the array that was passed in. In our case, it has to be a String, but the compiler isn’t smart enough to figure that out. For this reason, we cast the object to a String before using the equals() method.
    1First, we declare an array to hold references to NumberedThread -objects. Like any other type, we can make an array to hold objects that -inherit from Thread.Primeiro, declaramos uma matriz para manter referências aos objetos NumberedThread. Como qualquer outro tipo, podemos criar uma matriz para armazenar objetos que +herdam de Thread.
    2The first line of the for loop instantiates a -new NumberedThread object, invoking the constructor which stores the -current iteration of the loop into the value field. The reference to -each NumberedThread object is stored in the array. Remember that the -constructor does not start a new thread running.A primeira linha do loop for instancia um novo objeto NumberedThread, invocando o construtor que armazena a +iteração atual do loop no campo value. A referência a +cada objeto NumberedThread é armazenada na matriz. Lembre-se de que o construtor + não inicia a execução de uma nova thread.
    3The second line of the for loop does that.A segunda linha do loop for faz isso.
    4We’re also interested in when the threads stop. Calling the join() -method forces the main thread to wait for each thread to finish.Também estamos interessados em saber quando as threads param. A chamada do método join() +força a thread principal a aguardar a conclusão de cada thread.
    -

    The entire second for loop is nested inside of a try block. If the -main thread is interrupted while waiting for any of the threads to -finish, an InterruptedException will be caught. As before, we warn the -user that a thread didn’t finish. For production-quality code, the -catch block should handle the exception in such a way that the thread -can recover and do useful work even though it didn’t get what it was -waiting for.

    +

    Todo o segundo loop for está aninhado dentro de um bloco try. Se a thread principal for interrompida enquanto estiver aguardando a conclusão de qualquer uma das threads terminar, uma InterruptedException será capturada. Como antes, avisamos o usuário +que uma thread não foi concluída. Para código com qualidade de produção, o bloco +bloco catch deve tratar a exceção de forma que a thread possa se recuperar e fazer um trabalho útil, mesmo que não tenha obtido o resultado esperado.

    -

    13.5. Examples: Concurrency and speedup

    +

    13.5. Exemplos: Concorrência e aceleração

    -

    Speedup is one of the strongest motivations for writing concurrent -programs. To understand speedup, let’s assume we have a problem to -solve. We write two programs to solve this problem, one that’s -sequential and another that’s concurrent and, hence, able to exploit -multiple cores. Let ts be the average time to execute -the sequential program and tc the average time to execute -the concurrent program. So that the comparison is -meaningful, assume that both programs are executed on the same computer. -The speedup obtained from concurrent programming is defined as ts/tc.

    +

    A aceleração é uma das maiores motivações para escrever programas +concorrentes. Para entender o aumento de velocidade, vamos supor que temos um problema para +resolver. Escrevemos dois programas para resolver esse problema, um que é +sequencial e outro que é concorrente e, portanto, capaz de explorar +vários núcleos. Seja ts o tempo médio de execução do +o programa sequencial e tc o tempo médio de execução do programa concorrente. Para que a comparação seja +significativa, suponha que ambos os programas sejam executados no mesmo computador. +O aumento de velocidade obtido com a programação concorrente é definido como ts/tc.

    -

    Speedup measures how much faster the concurrent program executes -relative to the sequential program. Ideally, we expect -tc < ts, making the speedup greater than 1. However, -simply writing a concurrent program doesn’t guarantee that it’s faster -than the sequential version.

    +

    A aceleração mede quanto tempo leva para o programa concorrente ser executado em relação ao programa sequencial. Idealmente, esperamos que +tc < ts, tornando a aceleração maior que 1. No entanto, +simplesmente escrever um programa concorrente não garante que ele seja mais rápido +do que a versão sequencial.

    -

    To determine speedup, we need to measure ts and -tc. Time in a Java program can easily be measured with -the following two static methods in the System class.

    +

    Para determinar o aumento de velocidade, precisamos medir ts e tc. O +tempo em um programa Java pode ser facilmente medido com +os dois métodos estáticos a seguir na classe System.

    @@ -27938,27 +27907,23 @@

    13.5. Examples: Concurrency and speed

    -

    The first of these methods returns the current time in milliseconds -(ms). A millisecond is 0.001 seconds. This method gives the difference -between the current time on your computer’s clock and midnight of -January 1, 1970 Coordinated Universal Time (UTC). This point in time is -used for many timing features on many computer platforms and is called -the Unix epoch. The other method returns the current time in -nanoseconds (ns). A nanosecond is 0.000000001 or 10-9 seconds. This method also -gives the difference between the current time and some fixed time, which -is system dependent and not necessarily the Unix epoch. The -System.nanoTime() method can be used when you want timing precision -finer than milliseconds; however, the level of accuracy it returns is -again system dependent. The next example show how to use these methods -to measure execution time.

    +

    O primeiro desses métodos retorna a hora atual em milissegundos (ms). +Um millisecond equivale a 0,001 segundos. Esse método fornece a diferença +entre a hora atual no relógio de seu computador e a meia-noite de +1º de janeiro de 1970, horário universal coordenado (UTC). Esse ponto no tempo é +usado para muitos recursos de tempo em muitas plataformas de computador e é chamado de epoch Unix. O outro método retorna a hora atual em +nanossegundos (ns). Um nanossegundo equivale a 0,000000001 ou 10-9 segundos. +Esse método também fornece a diferença entre a hora atual e uma hora fixa, que depende do sistema e não necessariamente do epoch. +O método System.nanoTime() pode ser usado quando você quiser uma precisão de tempo +mais fina do que milissegundos; entretanto, o nível de precisão que ele retorna é +novamente dependente do sistema. O próximo exemplo mostra como usar esses métodos +para medir o tempo de execução.

    -
    Example 13.8 Measuring execution time
    +
    Exemplo 13.8 Medindo o tempo de execução
    -

    Suppose we want to measure the execution time of a piece of Java code. -For convenience, we can assume this code is contained in the work() -method. The following code snippet measures the time to execute +

    Suponha que desejemos medir o tempo de execução de um trecho de código Java. Por conveniência, podemos supor que esse código esteja contido no método work(). O trecho de código a seguir mede o tempo de execução de work().

    @@ -27966,41 +27931,41 @@

    13.5. Examples: Concurrency and speed
    long start = System.currentTimeMillis();
     work();
     long end = System.currentTimeMillis();
    -System.out.println("Elapsed time: " + (end - start) + " ms");
    +System.out.println("Tempo decorrido: " + (end - start) + " ms");

    -

    The output will give the execution time for work() measured in -milliseconds. To get the execution time in nanoseconds, use the -System.nanoTime() method instead.

    +

    A saída fornecerá o tempo de execução de work() medido em +milissegundos. Para obter o tempo de execução em nanossegundos, use o método +System.nanoTime() em vez de System.currentTimeMillis().

    -

    Now that we have the tools to measure execution time, we can measure -speedup. The next few examples show the speedup (or lack of it) that we -can achieve using a concurrent solution to a few simple problems.

    +

    Agora que temos as ferramentas para medir o tempo de execução, podemos medir o +aumento de velocidade. Os próximos exemplos mostram o aumento de velocidade (ou a falta dele) que podemos +podemos obter usando uma solução simultânea para alguns problemas simples.

    -
    Example 13.9 Math expression speedup
    +
    Exemplo 13.9 Acelerando o cálculo matemático
    -

    Recall the concurrent program in Example 13.6 to evaluate a simple mathematical expression. This program -uses two threads. We executed this multi-threaded program on an iMac -computer with an Intel Core 2 Duo running at 2.16 Ghz. The execution -time was measured at 1,660,000 nanoseconds. We also wrote a simple -sequential program to evaluate the same expression. It took 4,100 -nanoseconds to execute this program on the same computer. Plugging in -these values for tc and ts, we can find -the speedup.

    +

    Lembre-se do programa concorrente em Exemplo 13.6 para avaliar uma expressão matemática simples. Esse programa +usa duas threads. Executamos esse programa multithread em um computador iMac +com um Intel Core 2 Duo rodando a 2,16 Ghz. O tempo de execução +O tempo de execução foi medido em 1.660.000 nanossegundos. Também escrevemos um programa +programa sequencial simples para avaliar a mesma expressão. Foram necessários 4.100 +nanossegundos para executar esse programa no mesmo computador. Ao inserir +esses valores para tc e ts, podemos encontrar +a aceleração.

    @@ -28008,26 +27973,26 @@

    13.5. Examples: Concurrency and speed

    -

    This speedup is much less than 1. Although this result might be surprising, -the concurrent program with two threads executes slower than the -sequential program. In this example, the cost of creating, running, and -joining threads outweighs the benefits of concurrent calculation on two -cores.

    +

    Essa aceleração é muito menor que 1. Embora esse resultado possa ser surpreendente, +o programa concorrente com duas threads é executado mais lentamente do que o programa +sequencial. Nesse exemplo, o custo de criar, executar e +processar as threads supera os benefícios do cálculo simultâneo em dois +núcleos.

    -
    Example 13.10 Array summation
    +
    Exemplo 13.10 Somatório de matrizes
    -

    In Example 13.3, we introduced the +

    In Exemplo 13.3, we introduced the problem of applying a function to every value in an array and then summing the results. Let’s say that we want to apply the sine function to each value. To solve this problem concurrently, we partition the @@ -28209,17 +28174,17 @@

    13.5. Examples: Concurrency and speed
    -
    Example 13.11 Matrix multiplication
    +
    Exemplo 13.11 Matrix multiplication
    -

    In Example 13.4, we discussed the +

    In Exemplo 13.4, we discussed the importance of matrix operations in many applications. Now that we know the necessary Java syntax, we can write a concurrent program to multiply two square matrices A and B and compute the @@ -28416,8 +28381,8 @@

    13.5. Examples: Concurrency and speed @@ -28480,13 +28445,13 @@

    13.6.1. Nondeterminism

    balance many factors. If you create three threads, there’s no guarantee that the first will run first, the second second, and the third third, even if it happens that way the first 10 times you run the program. -Exercise 13.18 shows that the pattern of thread +Exercício 13.18 shows that the pattern of thread execution can vary a lot.

    @@ -28545,7 +28510,7 @@

    13.6.2. Polling

    @@ -28576,8 +28541,8 @@

    13.7. Syntax: Thread states

    @@ -28585,10 +28550,10 @@

    13.7. Syntax: Thread states

    thread states
    -
    Figure 13.7 Thread states and transitions.
    +
    Figura 13.7 Thread states and transitions.
    -

    Figure 13.7 shows the lifecycle of a thread. A +

    Figura 13.7 shows the lifecycle of a thread. A thread begins its life in the New Thread state, after the constructor is called. When the start() method is called, the thread begins to run and transitions to the Runnable state. Being Runnable doesn’t @@ -28630,7 +28595,7 @@

    13.7. Syntax: Thread states

    don’t use them unless and until you have a good reason.

    -
    Example 13.12 Military marching
    +
    Exemplo 13.12 Military marching

    Let’s apply the ideas discussed above to a lighthearted example. You @@ -28886,7 +28851,7 @@

    13.8. Solution: Deadly virus

    thread.

    -
    Program 13.1 Thread class used to find the sum of the two factors of a large odd composite.
    +
    Programa 13.1 Thread class used to find the sum of the two factors of a large odd composite.
    public class FactorThread extends Thread {  
         private long lower;
    @@ -28924,7 +28889,7 @@ 

    13.8. Solution: Deadly virus

    driver program Factor.

    -
    Program 13.2 Driver class which creates threads to lower the average search time for the factors of a large odd composite.
    +
    Programa 13.2 Driver class which creates threads to lower the average search time for the factors of a large odd composite.
    public class Factor {
         public static final int THREADS = 4; (1)
    @@ -29040,19 +29005,19 @@ 

    13.10. Exercises

  • Consider the expression in -Example 13.2. Suppose that the multiply and +Exemplo 13.2. Suppose that the multiply and exponentiation operations require 1 and 10 time units, respectively. Compute the number of time units required to evaluate the expression as -in Figure 13.2(a) and (b).

    +in Figura 13.2(a) and (b).

  • Suppose that a computer has one -quad-core processor. Can the tasks in [videoGameTasksExample] and Example 13.2 be further subdivided to +quad-core processor. Can the tasks in Exemplo 13.1 and Exemplo 13.2 be further subdivided to improve performance on four cores? Why or why not?

  • Consider the definition of speedup from -Section 13.5. Let’s assume you have a +[Examples: Concurrency and speedup]. Let’s assume you have a job 1,000,000 units in size. A thread can process 10,000 units of work every second. It takes an additional 100 units of work to create a new thread. What’s the speedup if you have a dual-core processor and create @@ -29141,7 +29106,7 @@

    13.10. Exercises

  • -

    Consider the following code snippet.

    +

    Consider the following code snippet.

    x = 13;
    @@ -29173,7 +29138,7 @@ 

    13.10. Exercises

    1. Re-implement the array summing problem from -Example 13.10 using polling instead of join() +Exemplo 13.10 using polling instead of join() calls. Your program should not use a single call to join(). Polling is not an ideal way to solve this problem, but it’s worth thinking about the technique.

    2. @@ -29276,7 +29241,7 @@

      13.10. Exercises

    3. Create serial and concurrent implementations of matrix multiplication like those described in -Example 13.11.

      +Exemplo 13.11.

      1. @@ -29293,7 +29258,7 @@

        13.10. Exercises

      2. Repeatedly run the code in -Example 13.7 which creates several +Exemplo 13.7 which creates several NumberedThread objects. Can you discover any patterns in the order that the threads print? Add a loop and some additional instrumentation to the NumberedThread class which will allow you to measure how long @@ -29301,7 +29266,7 @@

        13.10. Exercises

      3. Create serial and parallel implementations of -the array summing problem solved in Example 13.10. +the array summing problem solved in Exemplo 13.10. Experiment with different array sizes and thread counts to see how performance changes. How does the speedup differ from matrix multiply? What happens if you simply sum the numbers instead of taking the sine @@ -29309,7 +29274,7 @@

        13.10. Exercises

      4. The solution to the array summing problem in -Example 13.10 seems to use concurrency +Exemplo 13.10 seems to use concurrency half-heartedly. After all the threads have computed their sums, the main thread sums up the partial sums sequentially.

        @@ -29328,7 +29293,7 @@

        13.10. Exercises

        treesummation
        -
        Figure 13.8 Example of concurrent tree-style summation with 8 threads.
        +
        Figura 13.8 Example of concurrent tree-style summation with 8 threads.

        Update the run() method in the SumThread class so that it adds its @@ -29342,7 +29307,7 @@

        13.10. Exercises

        neighbor, and so on. Thread 0 will perform the final summation. Consequently, the main thread only needs to wait for thread 0. So that each thread can wait for other threads, the threads array will need to -be a static field. Figure 13.8 illustrates this +be a static field. Figura 13.8 illustrates this process.

        @@ -29405,13 +29370,13 @@

        14.2. Problem: Dining philosophers

        are single chopsticks so that there are exactly the same number of chopsticks as there are philosophers. These philosophers only think and eat. In order to eat, a philosopher must pick up both the chopstick on -her left and the chopstick on her right. Figure 14.1 illustrates this situation.

        +her left and the chopstick on her right. Figura 14.1 illustrates this situation.

        diners
        -
        Figure 14.1 Table for five dining philosophers.
        +
        Figura 14.1 Table for five dining philosophers.

        Your goal is to write a class called DiningPhilosopher which extends @@ -29435,7 +29400,7 @@

        14.3. Concepts: Thread interaction

        This dining philosopher problem highlights some difficulties which were emerging toward the end of the last chapter. In -[sharedThreadVariableExercise] two snippets of code could run +Exercício 13.10 two snippets of code could run concurrently and modify the same shared variable, potentially producing incorrect output. Because of the nondeterministic nature of scheduling, we have to assume that the code executing in two or more threads can be @@ -29444,7 +29409,7 @@

        14.3. Concepts: Thread interaction

        condition. Below is a simple example of a race condition in Java.

        -
        Program 14.1 Short example of a race condition.
        +
        Programa 14.1 Short example of a race condition.
        public class RaceCondition extends Thread {     
             private static int counter = 0; 
        @@ -29487,8 +29452,8 @@ 

        14.3. Concepts: Thread interaction

        @@ -29551,7 +29516,7 @@

        14.3. Concepts: Thread interaction

        @@ -29589,7 +29554,7 @@

        14.4.1. The synchronized keyword @@ -29605,7 +29570,7 @@

        14.4.1. The synchronized keyword @@ -29635,8 +29600,8 @@

        14.4.1. The synchronized keyword @@ -29806,13 +29771,13 @@

        14.4.2. The wait() and
        -
        Example 14.1 Producer/consumer
        +
        Exemplo 14.1 Producer/consumer

        To illustrate the use of wait() and notify() calls inside of @@ -29831,7 +29796,7 @@

        14.4.2. The wait() and buffer, but all accesses will be controlled.

        -
        Program 14.2 Example of a synchronized buffer.
        +
        Programa 14.2 Example of a synchronized buffer.
        public class Buffer {
             public final static int SIZE = 10;
        @@ -29905,12 +29870,12 @@ 

        14.4.2. The wait() and
        -
        Example 14.2 Bank account
        +
        Exemplo 14.2 Bank account

        Although producer/consumer is a good model to keep in mind, there are @@ -30100,7 +30065,7 @@

        14.5.1. Deadlock

      -
      Example 14.3 Deadlock philosophers
      +
      Exemplo 14.3 Deadlock philosophers

      We illustrate deadlock with an example of how not to solve the dining @@ -30250,7 +30215,7 @@

      14.5.1. Deadlock

      -
      Example 14.4 Deadlock sum
      +
      Exemplo 14.4 Deadlock sum

      Here’s another example of deadlock. We emphasize deadlock because it’s @@ -30383,7 +30348,7 @@

      14.5.1. Deadlock

      @@ -30404,7 +30369,7 @@

      14.5.2. Starvation and livelock

      Starvation doesn’t necessarily mean deadlock, however. Examine the -implementation in Example 14.2 for the bank account. +implementation in Exemplo 14.2 for the bank account. That solution is correct in the sense that it preserves mutual exclusion. No combination of balance checks, deposits, or withdrawals will cause the balance to be incorrect. Money will neither be created @@ -30418,7 +30383,7 @@

      14.5.2. Starvation and livelock

      @@ -30433,7 +30398,7 @@

      14.5.2. Starvation and livelock

      begin again and immediately stop. Lather, rinse, repeat.

      -
      Example 14.5 Livelock party preparations
      +
      Exemplo 14.5 Livelock party preparations

      Imagine three friends going to a party. Each of them starts @@ -30606,7 +30571,7 @@

      14.5.3. Sequential execution

      For example, we can take the run() method from the parallel -implementation of matrix multiply given in Example 13.11 +implementation of matrix multiply given in Exemplo 13.11 and use the synchronized keyword to lock on the matrix itself.

      @@ -30656,8 +30621,8 @@

      14.5.4. Priority inversion

      @@ -30697,7 +30662,7 @@

      14.6. Solution: Dining philosophers

      We begin with a similar setup as the deadlocking version given in -Example 14.3.

      +Exemplo 14.3.

      @@ -30800,7 +30765,7 @@

      14.6. Solution: Dining philosophers

      1 The real place where deadlock is prevented is in the getChopsticks() -method. As in Example 14.3, we mod by SEATS so that the last philosopher +method. As in Exemplo 14.3, we mod by SEATS so that the last philosopher tries to get the first chopstick in the array. @@ -30886,7 +30851,7 @@

      14.6. Solution: Dining philosophers

      @@ -30955,7 +30920,7 @@

      14.7. Exercises

    4. Examine our deadlock example from -Example 14.4. Explain why this example fulfills all +Exemplo 14.4. Explain why this example fulfills all four conditions for deadlock. Be specific about which threads and which resources are needed to show each condition.

    5. @@ -30972,7 +30937,7 @@

      14.7. Exercises

      1. In -Example 14.1 the Buffer class used to +Exemplo 14.1 the Buffer class used to implement a solution to the producer/consumer problem only has a single lock. When the buffer is empty and a producer puts an item in it, both producers and consumers are woken up. A similar situation happens @@ -30982,7 +30947,7 @@

        14.7. Exercises

        from a full buffer only wakes up producers.

      2. -

        In Example 14.2 +

        In Exemplo 14.2 we used the class SynchronizedAccount to solve a bank account problem. As we mention in Section 14.5.2, depositing and withdrawing threads can be starved out by a steady supply of balance @@ -31114,10 +31079,10 @@

        15.1. Problem: Math tutor

        mathTutorFigure
        -
        Figure 15.1 GUI for the MathTutor. (a) No menu selected. (b) Type selected. (c) Operations selected. (d) Attempting to answer an addition problem.
        +
        Figura 15.1 GUI for the MathTutor. (a) No menu selected. (b) Type selected. (c) Operations selected. (d) Attempting to answer an addition problem.
    -

    Figure 15.1 shows the final program in four +

    Figura 15.1 shows the final program in four different states. The window on the top left appears when the program is first initialized, with the “Submit” button disabled until a problem is generated. The top right and the bottom left show each of the two menus @@ -31331,14 +31296,14 @@

    15.3.1. Creating a frame

    -
    Example 15.1 Empty frame
    +
    Exemplo 15.1 Empty frame
    -

    Program 15.1 creates and displays an empty frame with +

    Programa 15.1 creates and displays an empty frame with the title “Empty Frame,” much like the code above.

    -
    Program 15.1 Creates an empty frame.
    +
    Programa 15.1 Creates an empty frame.
    import javax.swing.*; (1)
     
    @@ -31378,13 +31343,13 @@ 

    15.3.1. Creating a frame

    -

    The frame so created is shown in Figure 15.2.

    +

    The frame so created is shown in Figura 15.2.

    emptyFrameFigure
    -
    Figure 15.2 An empty frame titled “Empty Frame.”
    +
    Figura 15.2 An empty frame titled “Empty Frame.”

    You may resize the frame at any point in the program even after the @@ -31486,7 +31451,7 @@

    15.3.2. Components

    of the components we’ve introduced into one program.

    -
    Example 15.2 GUI with buttons and text field
    +
    Exemplo 15.2 GUI with buttons and text field

    We can write an application with a GUI that contains three buttons @@ -31501,7 +31466,7 @@

    15.3.2. Components

    useful.

    -
    Program 15.2 Creates a frame with a panel containing three buttons.
    +
    Programa 15.2 Creates a frame with a panel containing three buttons.
    import javax.swing.*;
     
    @@ -31557,7 +31522,7 @@ 

    15.3.2. Components

    -

    The final GUI is shown in Figure 15.3. The sequence in which you +

    The final GUI is shown in Figura 15.3. The sequence in which you add the buttons to the panel determines the appearance of the GUI. That’s why the text field appears before the “Exit” button. Note that the same GUI may look different on different platforms.

    @@ -31566,7 +31531,7 @@

    15.3.2. Components

    frameWithAPanelFigure
    -
    Figure 15.3 GUI consisting of a frame, a panel, three buttons, and a text field.
    +
    Figura 15.3 GUI consisting of a frame, a panel, three buttons, and a text field.
    @@ -31579,19 +31544,19 @@

    15.3.2. Components

    sensitive information like a password.

    -

    Figure 15.4(a) shows a GUI with a JTextArea, and -Figure 15.4(b) shows a GUI with a JPasswordField.

    +

    Figura 15.4(a) shows a GUI with a JTextArea, and +Figura 15.4(b) shows a GUI with a JPasswordField.

    textAreaAndPasswordFieldFigure
    -
    Figure 15.4 (a) GUI with a text area. (b) GUI with a password field.
    +
    Figura 15.4 (a) GUI with a text area. (b) GUI with a password field.
    @@ -31670,16 +31635,16 @@
    The ActionListener interface Section 9.4 and Section 10.4.

    -
    Example 15.3 GUI with actions
    +
    Exemplo 15.3 GUI with actions
    -

    Now we can modify Program 15.2 to respond to button +

    Now we can modify Programa 15.2 to respond to button clicks. When the thisButton button is clicked, the program will display the message “You can get with this.” in the text field. Similarly, when the thatButton button is clicked, the program will display “Or you can get with that.”

    -
    Program 15.3 Demonstrates handling of action events.
    +
    Programa 15.3 Demonstrates handling of action events.
    import javax.swing.*;
     import java.awt.event.*;
    @@ -31725,8 +31690,8 @@ 
    The ActionListener interface
    -

    Program 15.3 is largely the same as -Program 15.2. It adds the same buttons and text +

    Programa 15.3 is largely the same as +Programa 15.2. It adds the same buttons and text field but then adds an action listener to each button. The action performed when the thisButton and thatButton buttons are clicked is to display a message in the text box. When the exitButton button is clicked, the @@ -31740,7 +31705,7 @@

    The ActionListener interface
    -
    Example 15.4 GUI with alternate action listener style
    +
    Exemplo 15.4 GUI with alternate action listener style

    In the previous example, we added an ActionListener object to each @@ -31750,12 +31715,12 @@

    The ActionListener interface actionPerformed() method exactly once instead of creating several individual anonymous inner classes which each handle an event. Let’s examine one such implementation in -Program 15.4 and contrast it with -Program 15.3. Note that both programs +Programa 15.4 and contrast it with +Programa 15.3. Note that both programs generate the same GUI and exhibit identical behavior.

    -
    Program 15.4 Demonstrates handling of action events by implementing ActionListener at the class level.
    +
    Programa 15.4 Demonstrates handling of action events by implementing ActionListener at the class level.
    import javax.swing.*;
     import java.awt.event.*;
    @@ -31806,7 +31771,7 @@ 
    The ActionListener interface - + @@ -31831,8 +31796,8 @@
    The ActionListener interface

    There are a few differences between -Program 15.3 and -Program 15.4. In +Programa 15.3 and +Programa 15.4. In the second program, most of the code has been moved from the main() method to the constructor. Various objects, namely the frame, the panel, all three @@ -31854,7 +31819,7 @@

    The ActionListener interface @@ -31906,7 +31871,7 @@
    The ItemListener interface
    Below is an example of a GUI with three check boxes.

    -
    Example 15.5 GUI with check boxes
    +
    Exemplo 15.5 GUI with check boxes

    The following program shows a GUI with three check boxes labeled @@ -31998,14 +31963,14 @@

    The ItemListener interface
    -

    Figure 15.5 shows this GUI after the “Brutish” check box has +

    Figura 15.5 shows this GUI after the “Brutish” check box has been clicked.

    checkBoxExampleFigure
    -
    Figure 15.5 GUI consisting of a frame, a panel, three check boxes, and a text field.
    +
    Figura 15.5 GUI consisting of a frame, a panel, three check boxes, and a text field.

    All JCheckBox objects could have an ActionListener added to them @@ -32064,7 +32029,7 @@

    The ItemListener interface
    -
    Example 15.6 GUI with radio buttons
    +
    Exemplo 15.6 GUI with radio buttons

    The program below shows a GUI with three radio buttons labeled @@ -32166,9 +32131,9 @@

    The ItemListener interface
    -

    Figure 15.6(a) shows this GUI before any radio buttons -have been selected. Figure 15.6(b) shows this GUI after the -“Half full” radio button’s been selected. Figure 15.6(c) +

    Figura 15.6(a) shows this GUI before any radio buttons +have been selected. Figura 15.6(b) shows this GUI after the +“Half full” radio button’s been selected. Figura 15.6(c) shows this GUI after the “Twice the needed size” radio button’s been selected. In this final step, note that the second text field reads “And it’s not half full.” because the “Half full” button was just deselected.

    @@ -32177,7 +32142,7 @@
    The ItemListener interface
    radioButtonExampleFigure
    -
    Figure 15.6 GUI with radio buttons in three different states.
    +
    Figura 15.6 GUI with radio buttons in three different states.
    @@ -32235,7 +32200,7 @@
    The MouseListener interfaceMouseListener in use.

    -
    Example 15.7 Mouse listener
    +
    Exemplo 15.7 Mouse listener

    We can write a program that displays a GUI containing two buttons labeled @@ -32245,7 +32210,7 @@

    The MouseListener interface
    -
    Program 15.5 Demonstrates the handling of mouse generated events using the MouseListener interface.
    +
    Programa 15.5 Demonstrates the handling of mouse generated events using the MouseListener interface.
    import javax.swing.*;
     import java.awt.*;
    @@ -32332,21 +32297,21 @@ 
    The MouseListener interface
    -

    Program 15.5 generates the GUI shown in -Figure 15.7.

    +

    Programa 15.5 generates the GUI shown in +Figura 15.7.

    simpleMouseEventsFigure
    -
    Figure 15.7 GUI consisting of two buttons and a text box. Button clicks and entry of the cursor into a button are reported by the text box.
    +
    Figura 15.7 GUI consisting of two buttons and a text box. Button clicks and entry of the cursor into a button are reported by the text box.
    @@ -32355,7 +32320,7 @@
    The MouseListener interfaceMouse adapter

    Creating a MouseListener requires all five methods in the interface to -be implemented. In many cases, as in Example 15.7, +be implemented. In many cases, as in Exemplo 15.7, there’s no need to implement all the methods because we’re not interested in all the corresponding events. In such situations we’re forced to include empty methods. @@ -32371,15 +32336,15 @@

    Mouse adapter
    don’t need to provide an implementation of a method that’s not used.

    -
    Example 15.8 Mouse adapter
    +
    Exemplo 15.8 Mouse adapter
    -

    Program 15.6 is a revised version of -Program 15.5. Remember that an abstract class is +

    Programa 15.6 is a revised version of +Programa 15.5. Remember that an abstract class is extended whereas an interface is implemented.

    -
    Program 15.6 Handles mouse generated events using the MouseAdapter abstract class.
    +
    Programa 15.6 Handles mouse generated events using the MouseAdapter abstract class.
    import javax.swing.*;
     import java.awt.*;
    @@ -32451,7 +32416,7 @@ 
    Mouse adapter
    @@ -32568,7 +32533,7 @@
    Sounds
    clip, we’re ready to write a program that can play sounds.

    -
    Example 15.9 Animal sounds
    +
    Exemplo 15.9 Animal sounds

    We can write a program to play a loop of a bird chirping or a dog barking @@ -32579,16 +32544,16 @@

    Sounds
    animalSoundsFigure
    -
    Figure 15.8 GUI for the animal sounds application. (a) On program start. (b) After the “Chirp” button has been clicked and the clip is playing.
    +
    Figura 15.8 GUI for the animal sounds application. (a) On program start. (b) After the “Chirp” button has been clicked and the clip is playing.

    We can include a button labeled “Stop Sound” that stops the playback of sounds when clicked. When it starts, the GUI will look like -Figure 15.8(a). Note that the “Stop Sound” button is gray, +Figura 15.8(a). Note that the “Stop Sound” button is gray, showing that it’s disabled. The complete program is shown below.

    -
    Program 15.7 Animal sounds
    +
    Programa 15.7 Animal sounds
    import java.io.*;  (1)
     import java.awt.event.*;
    @@ -32696,15 +32661,15 @@ 
    Sounds
    1The constructor adds an ActionListener to each button. The listener added is this, specifying that the AlternateActionListener object is the one that will process any action event generated by the buttons. The remainder of the code for the constructor is essentially the same as that from the main() method in Program 15.3.The constructor adds an ActionListener to each button. The listener added is this, specifying that the AlternateActionListener object is the one that will process any action event generated by the buttons. The remainder of the code for the constructor is essentially the same as that from the main() method in Programa 15.3.
    2
    -

    When chirpButton is clicked, the GUI looks like Figure 15.8(b).

    +

    When chirpButton is clicked, the GUI looks like Figura 15.8(b).

    @@ -32743,26 +32708,26 @@
    Images and icons
    -
    Example 15.10 Icon example
    +
    Exemplo 15.10 Icon example
    -

    Figure 15.9 shows a GUI with a button decorated with a -picture. Program 15.8 gives the code to create this +

    Figura 15.9 shows a GUI with a button decorated with a +picture. Programa 15.8 gives the code to create this GUI using the ImageIcon class.

    iconExampleFigure
    -
    Figure 15.9 A GUI with a button decorated by an image icon.
    +
    Figura 15.9 A GUI with a button decorated by an image icon.
    -
    Program 15.8 Creates a GUI with a button decorated by a picture.
    +
    Programa 15.8 Creates a GUI with a button decorated by a picture.
    import javax.swing.*;
     import java.awt.*;
    @@ -32801,7 +32766,7 @@ 
    Images and icons
    @@ -32850,19 +32815,19 @@
    Labels, icons, and text
    -
    Example 15.11 Label example
    +
    Exemplo 15.11 Label example
    -

    Figure 15.10(a) is generated by Program 15.9.

    +

    Figura 15.10(a) is generated by Programa 15.9.

    labelExampleFigure
    -
    Figure 15.10 (a) A GUI with a label decorated by an image icon and a title beneath it. (b) The GUI with unaligned text.
    +
    Figura 15.10 (a) A GUI with a label decorated by an image icon and a title beneath it. (b) The GUI with unaligned text.
    -
    Program 15.9 Creates a GUI with a label decorated by a picture and text.
    +
    Programa 15.9 Creates a GUI with a label decorated by a picture and text.
    import javax.swing.*;
     import java.awt.*;
    @@ -32896,7 +32861,7 @@ 
    Labels, icons, and text

    You will see the GUI shown in -Figure 15.10(b) if the alignment instructions on these two lines are omitted.

    +Figura 15.10(b) if the alignment instructions on these two lines are omitted.

    @@ -32938,14 +32903,14 @@
    FlowLayout
    earlier examples. The next example illustrates FlowLayout further.

    -
    Example 15.12 FlowLayout
    +
    Exemplo 15.12 FlowLayout
    -

    Program 15.10 creates a GUI with several +

    Programa 15.10 creates a GUI with several buttons.

    -
    Program 15.10 Adds several buttons using FlowLayout.
    +
    Programa 15.10 Adds several buttons using FlowLayout.
    import javax.swing.*;
     import java.awt.*;
    @@ -32985,21 +32950,21 @@ 
    FlowLayout

    The FlowLayout manager places the buttons along a number of rows depending on the width of the frame. If the container changes size, the components will react by "'flowing'" into different rows, hence the name. -The GUI created is shown in Figure 15.11.

    +The GUI created is shown in Figura 15.11.

    flowLayoutFigure
    -
    Figure 15.11 Using the FlowLayout manager to generate a GUI containing six buttons.
    +
    Figura 15.11 Using the FlowLayout manager to generate a GUI containing six buttons.
    @@ -33029,12 +32994,12 @@
    GridLayout
    gridLayoutFigure
    -
    Figure 15.12 A 3 × 2 grid layout containing six buttons.
    +
    Figura 15.12 A 3 × 2 grid layout containing six buttons.
    -

    Figure 15.12 shows how frame will look after six +

    Figura 15.12 shows how frame will look after six buttons, labeled 0 through 5, have been added to it in order. The buttons -were created in the same way as the buttons in Program 15.10, but +were created in the same way as the buttons in Programa 15.10, but they look different because of the GridLayout manager. A key feature of using GridLayout is that all cells in the grid will be the same size and will stretch to fill the entire container. Also note @@ -33045,31 +33010,31 @@

    GridLayout
    -
    Example 15.13 Animal identifier
    +
    Exemplo 15.13 Animal identifier

    We can write a program to display pictures of animals and identify which animal the mouse is current hovering over. The animal’s name will be displayed in the title of the frame. -Figure 15.13 shows this GUI.

    +Figura 15.13 shows this GUI.

    animalIdentifierFigure
    -
    Figure 15.13 A GUI for an animal identifier. Note that the bison is identified according to the frame title.
    +
    Figura 15.13 A GUI for an animal identifier. Note that the bison is identified according to the frame title.
    -

    Program 15.11 creates the GUI shown in -Figure 15.13.

    +

    Programa 15.11 creates the GUI shown in +Figura 15.13.

    -
    Program 15.11 Identifies which animal is in various images when the mouse hovers over the image. Images are laid out using a GridLayout manager.
    +
    Programa 15.11 Identifies which animal is in various images when the mouse hovers over the image. Images are laid out using a GridLayout manager.
    import javax.swing.*;
     import java.awt.*;
    @@ -33171,7 +33136,7 @@ 
    GridLayout
    -

    Play with Program 15.11. What happens when you +

    Play with Programa 15.11. What happens when you resize the window?

    @@ -33179,7 +33144,7 @@
    GridLayout
    @@ -33205,7 +33170,7 @@
    BorderLayout
    stretch as big as it needs to fill the container.

    -
    Example 15.14 BorderLayout
    +
    Exemplo 15.14 BorderLayout

    Here’s an example of a frame using BorderLayout. Five buttons have @@ -33213,7 +33178,7 @@

    BorderLayout
    we don’t need to state it explicitly, although we do in this case.

    -
    Program 15.12 Shows buttons laid out in each of the five regions of a BorderLayout.
    +
    Programa 15.12 Shows buttons laid out in each of the five regions of a BorderLayout.
    import javax.swing.*;
     import java.awt.*;
    @@ -33238,7 +33203,7 @@ 
    BorderLayout
    borderLayoutFigure
    -
    Figure 15.14 A GUI demonstrating BorderLayout generated by Program 15.12.
    +
    Figura 15.14 A GUI demonstrating BorderLayout generated by Programa 15.12.

    Unlike FlowLayout or GridLayout, the location must be specified to @@ -33262,7 +33227,7 @@

    BorderLayout
    example.

    -
    Example 15.15 Calculator layout
    +
    Exemplo 15.15 Calculator layout

    We can make a GUI application that functions as a simple calculator. The @@ -33275,7 +33240,7 @@

    BorderLayout
    is given below.

    -
    Program 15.13 Lays out a simple calculator.
    +
    Programa 15.13 Lays out a simple calculator.
    import javax.swing.*;
     import java.awt.*;
    @@ -33313,7 +33278,7 @@ 
    BorderLayout
    calculatorLayoutFigure
    -
    Figure 15.15 GUI generated by Program 15.13.
    +
    Figura 15.15 GUI generated by Programa 15.13.

    This program uses a frame with a BorderLayout to arrange components around @@ -33333,7 +33298,7 @@

    BorderLayout
    @@ -33435,19 +33400,19 @@
    Creating menus
    JMenuBar to the regular content area, not to the menu area.

    -

    Figure 15.16 shows a GUI with the menus and menu items added above.

    +

    Figura 15.16 shows a GUI with the menus and menu items added above.

    @@ -33464,7 +33429,7 @@
    Creating menus

    These statements create a menu item named unusable and disable it. A disabled menu item shows as a gray item and doesn’t respond to -attempts to select it. As we showed in Example 15.9, JButton +attempts to select it. As we showed in Exemplo 15.9, JButton objects, like many other components, can be disabled in the same way.

    @@ -33500,11 +33465,11 @@
    Adding events to menus

    15.4. Solution: Math tutor

    Here we give the code to generate the GUI shown in -Figure 15.1 which displays basic (addition and +Figura 15.1 which displays basic (addition and subtraction) as well as advanced (multiplication and division) problems.

    -

    As shown in Figure 15.1, this GUI has a menu bar +

    As shown in Figura 15.1, this GUI has a menu bar consisting of two menus labeled “Type” and “Operations.” The “Type” menu contains a check box labeled “Advanced” while the “Operations” menu contains four menu items labeled “Add,” @@ -33519,7 +33484,7 @@

    15.4. Solution: Math tutor

    integers.

    -
    Program 15.14 Utility class to generate random addition, subtraction, multiplication, and division problems.
    +
    Programa 15.14 Utility class to generate random addition, subtraction, multiplication, and division problems.
    import java.util.Random;
     import javax.swing.*;
    @@ -33566,11 +33531,11 @@ 

    15.4. Solution: Math tutor

    symbols.

    -

    Program 15.15 generates the GUI in -Figure 15.1.

    +

    Programa 15.15 generates the GUI in +Figura 15.1.

    -
    Program 15.15 Uses menus to generate math problems.
    +
    Programa 15.15 Uses menus to generate math problems.
    import javax.swing.*;
     import java.awt.*;
    @@ -33814,7 +33779,7 @@ 

    15.5.1. Worker threads

    a counter and displays the value in the second label.

    -
    Program 15.16 GUI that becomes unresponsive when the “Compute” button is pressed.
    +
    Programa 15.16 GUI that becomes unresponsive when the “Compute” button is pressed.
    import javax.swing.*;
     import java.awt.*;
    @@ -33866,7 +33831,7 @@ 

    15.5.1. Worker threads

    unresponsiveGUIFigure
    -
    Figure 15.17 GUI generated by Program 15.16.
    +
    Figura 15.17 GUI generated by Programa 15.16.

    If you click the “Compute” button, the GUI becomes unresponsive. @@ -33880,8 +33845,8 @@

    15.5.1. Worker threads

    @@ -33900,10 +33865,10 @@

    15.5.1. Worker threads

    periodically in the process of doing work (which can be useful for updating progress bars). Examine the following program which has added a SwingWorker to its actionPerformed() method but is otherwise the -same as Program 15.16.

    +same as Programa 15.16.

    -
    Program 15.17 GUI that uses SwingWorker to avoid becoming unresponsive.
    +
    Programa 15.17 GUI that uses SwingWorker to avoid becoming unresponsive.
    import javax.swing.*;
     import java.awt.*;
    @@ -34011,7 +33976,7 @@ 

    15.5.1. Worker threads

    @@ -34071,14 +34036,14 @@

    15.7. Exercises

    should be titled “Start and Done.”

  • -

    Modify Program 15.5 by implementing +

    Modify Programa 15.5 by implementing the mouseExited(), mousePressed(), and mouseReleased() methods. Each method must display a suitable message in the text box when the corresponding event occurs. For example, when the mouse exits button one, the text box should display “Mouse exits One.”

  • -

    Modify Program 15.8 such that clicking the +

    Modify Programa 15.8 such that clicking the icon-decorated button plays the sound of a bat squeaking. You will need to add an ActionListener to the button, create an audio clip for the desired sound, and then play this clip when the button is clicked. Consider @@ -34090,24 +34055,24 @@

    15.7. Exercises

  • Extend the AnimalSounds class -developed in Example 15.9 to include sounds for +developed in Exemplo 15.9 to include sounds for various animals. There are many publicly available sounds files for use in your program. The Freesound link above is only one source.

  • -

    In Example 15.9 we stopped both the +

    In Exemplo 15.9 we stopped both the chirp and the bark sounds because the action listener corresponding to the “Stop Playing” button didn’t know which sound was playing. Modify -Program 15.7 so that only the sound that’s playing is stopped. +Programa 15.7 so that only the sound that’s playing is stopped. You may need to declare another variable to keep track of which is playing.

  • -

    Modify Program 15.11 so that it plays +

    Modify Programa 15.11 so that it plays a sound associated with an animal when the mouse is clicked over its label. Note that this is an example of a situation where a MouseListener can be used to listen for mouse click events though an ActionListener cannot. As in -Exercise 15.7 and Exercise 15.9, you may need to download +Exercício 15.7 and Exercício 15.9, you may need to download sounds from the Internet.

  • @@ -34133,14 +34098,14 @@

    15.7. Exercises

  • In -Program 15.3 exchange the first two +Programa 15.3 exchange the first two add() method calls on the panel so that thatButton is added to the panel before thisButton. Explain how the appearance of the GUI is changed.

  • Modify -Program 15.2 by adding a second panel named +Programa 15.2 by adding a second panel named secondPanel. Create a new button named otherButton with the label “The Other.” Add otherButton to secondPanel. Now add secondPanel to frame and look at the GUI generated. Can you explain why only components @@ -34148,13 +34113,13 @@

    15.7. Exercises

  • Remove the line frame.setResizable(false); from -Program 15.10. Run the modified program and +Programa 15.10. Run the modified program and resize the frame to various sizes. How does the placement of the buttons change?

  • Modify -Program 15.10 by deleting the lines that set the +Programa 15.10 by deleting the lines that set the frame size. What does the resulting GUI look like? Now add the following code just before the line frame.setResizable(false);:

    @@ -34179,7 +34144,7 @@

    15.7. Exercises

  • Consider the calculator layout from -Program 15.13. Add listeners to all of its buttons so that +Programa 15.13. Add listeners to all of its buttons so that clicking on the number buttons, the plus and minus buttons, and the “Enter” button will make it perform like a calculator capable of addition and subtraction. Note that you’ll need to add some additional fields to keep @@ -34202,25 +34167,25 @@

    15.7. Exercises

    1. -

      Recall that Program 15.16 is +

      Recall that Programa 15.16 is unresponsive because the event dispatch thread goes to sleep for 5 seconds (5,000 milliseconds). Experiment with this value to determine how much time you can block the EDT before the GUI feels unresponsive.

    2. -

      Program 15.16 is +

      Programa 15.16 is unrealistic because the EDT simply goes to sleep. Normally, a GUI becomes unresponsive because the EDT is performing extensive calculations or doing slow I/O operations. Replace the line that sleeps with a short loop that performs significant calculations. One simple way to spend a lot of computational time is by summing the sines of random numbers, similar -to the work done in Example 13.10. How many sines do you need to +to the work done in Exemplo 13.10. How many sines do you need to compute to make the GUI unresponsive for 5 seconds?

    3. Take the computationally expensive loop -from Exercise 15.22 and use it to replace the line that sleeps in -Program 15.17, the SwingWorker version of the program. Does the +from Exercício 15.22 and use it to replace the line that sleeps in +Programa 15.17, the SwingWorker version of the program. Does the program become unresponsive if you run it? If possible, run the program on Windows, macOS, and Linux environments. If it’s unresponsive in some environments but not others, why do you think that might be?

      @@ -34566,7 +34531,7 @@

      16.3.1. Assertions

      @@ -34797,7 +34762,7 @@

      16.3.4. Examples

      few examples corresponding to the common bugs listed in Section 16.1.

    -
    Example 16.1 Precision errors
    +
    Exemplo 16.1 Precision errors

    Floating-point precision can cause subtle errors. @@ -34831,7 +34796,7 @@

    16.3.4. Examples

    -
    Example 16.2 Overflow and underflow
    +
    Exemplo 16.2 Overflow and underflow

    As you know, the int and long types have limited bits for @@ -34916,7 +34881,7 @@

    16.3.4. Examples

    -
    Example 16.3 Casting errors
    +
    Exemplo 16.3 Casting errors

    The previous example about scaling color component values shows one of the @@ -34994,7 +34959,7 @@

    16.3.4. Examples

    errors.

    -
    Example 16.4 Off-by-one errors
    +
    Exemplo 16.4 Off-by-one errors

    Computer scientists often use zero-based counting. This departure from @@ -35059,7 +35024,7 @@

    16.3.4. Examples

    -
    Example 16.5 Infinite loops
    +
    Exemplo 16.5 Infinite loops

    Infinite loops come in many different flavors, from the char overflow @@ -35146,7 +35111,7 @@

    16.3.4. Examples

    -
    Example 16.6 Zero loops
    +
    Exemplo 16.6 Zero loops

    On the other end of the spectrum, a bad condition can make a loop @@ -35224,7 +35189,7 @@

    16.3.4. Examples

    -
    Example 16.7 Equivalence testing errors
    +
    Exemplo 16.7 Equivalence testing errors

    Equivalence is tricky in Java. Very inexperienced programmers confuse @@ -35294,7 +35259,7 @@

    16.3.4. Examples

    applications depend on the efficient and correct operation of hash tables. Hash tables are data structures used to store and retrieve a key and an associated value. We’ll discuss them briefly -in Example 18.4.

    +in Exemplo 18.4.

    @@ -35310,7 +35275,7 @@

    16.3.5. Array errors

    to reconstruct what it is.

    -
    Example 16.8 Out of bounds
    +
    Exemplo 16.8 Out of bounds

    We have all experienced an ArrayIndexOutOfBoundsException. Either a @@ -35361,7 +35326,7 @@

    16.3.5. Array errors

    -
    Example 16.9 Uninitialized object arrays
    +
    Exemplo 16.9 Uninitialized object arrays

    Another simple mistake that can occur with arrays is failing to @@ -35405,7 +35370,7 @@

    16.3.6. Scope errors

    accessing at any given time can appear obvious, even if it really isn’t.

    -
    Example 16.10 Shadowing variables
    +
    Exemplo 16.10 Shadowing variables

    Java allows variables in different scopes to be declared with the same @@ -35534,7 +35499,7 @@

    16.3.6. Scope errors

    -
    Example 16.11 Reference vs. value
    +
    Exemplo 16.11 Reference vs. value

    The final category of scope error we’ll talk about occurs when using @@ -36010,7 +35975,7 @@

    Black-box testing
    @@ -36051,7 +36016,7 @@
    White-box testing
    @@ -36251,14 +36216,14 @@
    Basic JUnit syntax
    including a delta threshold in case the values don’t match exactly.

    -
    Example 16.12 JUnit math testing
    +
    Exemplo 16.12 JUnit math testing

    Using these methods, we can finally write a complete (though simple) implementation of MathTest.java.

    -
    Program 16.1 Simple testing suite.
    +
    Programa 16.1 Simple testing suite.
    import org.junit.jupiter.api.*;
     import static org.junit.jupiter.api.Assertions.*;
    @@ -36496,7 +36461,7 @@ 

    16.9. Examples: Testing a class

    example of JUnit testing.

    -
    Example 16.13 A broken class
    +
    Exemplo 16.13 A broken class

    Using an example from physics, we can create a PointCharge class that has @@ -36506,7 +36471,7 @@

    16.9. Examples: Testing a class

    might come up in real development.

    -
    Program 16.2 Physics class with errors.
    +
    Programa 16.2 Physics class with errors.
    public class PointCharge {  
         private double charge;  // C
    @@ -36599,7 +36564,7 @@ 

    16.9. Examples: Testing a class

    -
    Example 16.14 Testing the distance methods
    +
    Exemplo 16.14 Testing the distance methods

    Let’s come up with a test for the distance() methods first. We’re @@ -36695,7 +36660,7 @@

    16.9. Examples: Testing a class

    -
    Example 16.15 Testing the field magnitude method
    +
    Exemplo 16.15 Testing the field magnitude method

    Finally, let’s test the value of the fieldMagnitude() method. For @@ -36725,7 +36690,7 @@

    16.9. Examples: Testing a class

    FixedPointCharge.

    -
    Program 16.3 Corrected version of PointCharge.
    +
    Programa 16.3 Corrected version of PointCharge.
    public class FixedPointCharge {  
     	private double charge;  // C
    @@ -36773,7 +36738,7 @@ 

    16.9. Examples: Testing a class

    class.

    -
    Program 16.4 Class for testing PointCharge.
    +
    Programa 16.4 Class for testing PointCharge.
    import org.junit.jupiter.api.*;
     import static org.junit.jupiter.api.Assertions.*;
    @@ -37162,8 +37127,8 @@ 

    17.2.2. Dynamic binding

    @@ -37336,7 +37301,7 @@

    17.3.1. Abstract classes and methods

    @@ -37407,7 +37372,7 @@

    17.3.1. Abstract classes and methods

    but unlike interfaces they can also define fields and methods of any kind.

    -
    Example 17.1 Bank account abstract class
    +
    Exemplo 17.1 Bank account abstract class

    Here’s a more involved example of an abstract class that gives a first @@ -37679,7 +37644,7 @@

    17.3.3. Casting

    @@ -37752,12 +37717,12 @@

    17.3.4. Inheritance and exceptions

    -
    Example 17.2 More human than human
    +
    Exemplo 17.2 More human than human

    Here we have a few additional examples in a somewhat larger class @@ -37767,7 +37732,7 @@

    17.3.4. Inheritance and exceptions

    animals
    -
    Figure 17.1 Animal class hierarchy.
    +
    Figura 17.1 Animal class hierarchy.
    @@ -37914,10 +37879,10 @@

    17.4. Solution: Banking acco
    accounts
    -
    Figure 17.2 Bank account class hierarchy.
    +
    Figura 17.2 Bank account class hierarchy.

    -
    Program 17.1 Child class of BankAccount that models a normal checking account.
    +
    Programa 17.1 Child class of BankAccount that models a normal checking account.
    public class CheckingAccount extends BankAccount {
         public static final double FEE = 10;
    @@ -37966,7 +37931,7 @@ 

    17.4. Solution: Banking acco due to the next class.

    -
    Program 17.2 Child class of CheckingAccount that models the behavior of accounts with direct deposits.
    +
    Programa 17.2 Child class of CheckingAccount that models the behavior of accounts with direct deposits.
    import java.util.Calendar;
     public class DirectDepositAccount extends CheckingAccount {
    @@ -38008,7 +37973,7 @@ 

    17.4. Solution: Banking acco overridden getFee() method for DirectDepositAccount objects.

    -
    Program 17.3 Child class of BankAccount that models the behavior of a savings account.
    +
    Programa 17.3 Child class of BankAccount that models the behavior of a savings account.
    public class SavingsAccount extends BankAccount {
         public static final double MINIMUM = 1000;
    @@ -38077,20 +38042,20 @@ 

    17.5. Concurrency: Atomic libraries

    the AtomicInteger class encapsulates the functionality of an int variable with atomic accesses. One of its methods is incrementAndGet(), which will atomically increment its internal value by 1 and return the result. Recall from -Program 14.1 that even an operation as simple as +Programa 14.1 that even an operation as simple as ++ isn’t atomic. If many different threads try to increment a single variable, some of those increments can get lost, causing the final value to be less than it should be.

    -
    Example 17.3 AtomicInteger
    +
    Exemplo 17.3 AtomicInteger

    We can use the AtomicInteger class to rewrite -Program 14.1 so that no race condition occurs.

    +Programa 14.1 so that no race condition occurs.

    -
    Program 17.4 Demonstrates the use of AtomicInteger.
    +
    Programa 17.4 Demonstrates the use of AtomicInteger.
    import java.util.concurrent.atomic.*;
     
    @@ -38123,7 +38088,7 @@ 

    17.5. Concurrency: Atomic libraries

    -

    This program is identical to Program 14.1, except +

    This program is identical to Programa 14.1, except that the type of counter has been changed from int to AtomicInteger (and an appropriate import has been added). Consequently, the ++ operation was changed to an incrementAndGet() @@ -38136,7 +38101,7 @@

    17.5. Concurrency: Atomic libraries

    @@ -38164,7 +38129,7 @@

    17.5. Concurrency: Atomic libraries

    @@ -38378,7 +38343,7 @@

    17.6. Exercises

  • Re-implement the original -SynchronizedAccount class from Example 14.2 using +SynchronizedAccount class from Exemplo 14.2 using atomic classes. For simplicity, you can change the balance type from double to AtomicInteger since there’s no AtomicDouble class. How much has this simplified the implementation? Is the readers field @@ -38392,11 +38357,11 @@

    17.6. Exercises

    1. -

      Take Program 17.4 +

      Take Programa 17.4 and increase COUNT to 100000000. Run it several times and time how long it takes to run to completion.

      -

      Then, take Program 14.1 and increase its COUNT to +

      Then, take Programa 14.1 and increase its COUNT to 100000000 as well. Change the body of the for loop inside the run() method so that count++; is inside of a synchronized block that uses RaceCondition.class as the lock. (The choice of @@ -38607,7 +38572,7 @@

      18.2.1. Dynamic arrays

      dynamicinsertion
      -
      Figure 18.1 Insertion into full dynamic array requiring reallocation. Even if the array wasn’t full, all values after 14 would need to be moved back to insert 17 in order.
      +
      Figura 18.1 Insertion into full dynamic array requiring reallocation. Even if the array wasn’t full, all values after 14 would need to be moved back to insert 17 in order.

      Another drawback of dynamic arrays is that they’re poorly suited for @@ -38632,7 +38597,7 @@

      18.2.2. Linked lists

      linkedlist
      -
      Figure 18.2 Visualization of a linked list.
      +
      Figura 18.2 Visualization of a linked list.

      Linked lists are flexible because they have no preset size. Whenever a @@ -38719,7 +38684,7 @@

      18.3.1. Dynamic arrays

      A simple solution
      -

      Program 18.1 allocates an array of 10 String references +

      Programa 18.1 allocates an array of 10 String references and reads a list of names from standard input until it reaches the end of the file, storing each name in successive array locations. If the number of names in the input is larger than the size of the array, it @@ -38734,7 +38699,7 @@

      A simple solution
      message before exiting.

      -
      Program 18.1 Reads names into an array, sort, and print. If there are more than 10 lines in the input, an exception is generated.
      +
      Programa 18.1 Reads names into an array, sort, and print. If there are more than 10 lines in the input, an exception is generated.
      import java.util.Arrays;
       import java.util.Scanner;
      @@ -38779,16 +38744,16 @@ 
      A simple solution
      -

      Program 18.2 begins like the previous program by +

      Programa 18.2 begins like the previous program by allocating a fixed-size array.

      -
      Program 18.2 Reads names into an array, enlarging the array as necessary.
      +
      Programa 18.2 Reads names into an array, enlarging the array as necessary.
      import java.util.Arrays;
       import java.util.Scanner;
      @@ -38837,7 +38802,7 @@ 
      A simple solution

      Note that it was necessary to refactor the code in -Program 18.1 slightly. We added the line variable +Programa 18.1 slightly. We added the line variable to hold the temporary result of reading the input line and moved the count increment outside of the try-catch block.

      @@ -38849,7 +38814,7 @@
      A simple solution
      @@ -38866,13 +38831,13 @@
      A simple solution

      This line works because we know the only variable that references the array is names. If other variables referenced that array, they would continue to reference the old, smaller, and now out-of-date version of -the names array. Figure 18.3 shows this problem.

      +the names array. Figura 18.3 shows this problem.

      dynamicproblems
      -
      Figure 18.3 A poorly designed dynamic array implementation. (a) Both array1 and array2 begin pointing at the same array. (b) A new array has been allocated, and 42 has been added to it. array1 has been updated to point at the new array, but array2 still points at the original.
      +
      Figura 18.3 A poorly designed dynamic array implementation. (a) Both array1 and array2 begin pointing at the same array. (b) A new array has been allocated, and 42 has been added to it. array1 has been updated to point at the new array, but array2 still points at the original.
      @@ -38888,13 +38853,13 @@
      A more complete solution

      A solution to this problem is to create a new class whose objects contain the array as a private field. References to the array are then mediated, as usual, via accessor methods, which always refers to the -same version of the array. Program 18.3 is a simple +same version of the array. Programa 18.3 is a simple implementation of a dynamic array class. This class maintains an internal array of String objects, which it extends whenever a call to set() tries to write a new element just past the end of the array.

      -
      Program 18.3 Class to manage a dynamic array. This array grows by doubling when more space is needed.
      +
      Programa 18.3 Class to manage a dynamic array. This array grows by doubling when more space is needed.
      import java.util.Arrays;
       
      @@ -38924,14 +38889,14 @@ 
      A more complete solution
      -

      Program 18.4 illustrates how to modify and extend -Program 18.1 to use this new class. Since the +

      Programa 18.4 illustrates how to modify and extend +Programa 18.1 to use this new class. Since the array grows automatically, there is no need for the original program to check for out-of-bounds exceptions. Of course, the array expansion only works if the reference occurs exactly at the index corresponding to one @@ -38939,7 +38904,7 @@

      A more complete solution
      exception.

      -
      Program 18.4 Uses the DynamicArray class to store input read from a file.
      +
      Programa 18.4 Uses the DynamicArray class to store input read from a file.
      import java.util.Scanner;
       
      @@ -38995,7 +38960,7 @@ 
      A more complete solution
      @@ -39071,7 +39036,7 @@
      Constructing a linked list
      fills an array with the values in the list.

      -
      Program 18.5 Basic implementation of a linked list class to hold String objects.
      +
      Programa 18.5 Basic implementation of a linked list class to hold String objects.
      public class LinkedList {
           private static class Node {
      @@ -39106,13 +39071,13 @@ 
      Constructing a linked list
      -

      Program 18.6 is a re-implementation of the +

      Programa 18.6 is a re-implementation of the name-reading program using class LinkedList. Note that no array needs to be pre-allocated. Instead, we capture all lines of input in a linked list called list.

      -
      Program 18.6 Uses the LinkedList class to store input read from a file.
      +
      Programa 18.6 Uses the LinkedList class to store input read from a file.
      import java.util.Arrays;
       import java.util.Scanner;
      @@ -39147,7 +39112,7 @@ 
      Constructing a linked list
      String read in, has a next value of null.

      -

      Figure 18.4 shows a visualization of the contents of this +

      Figura 18.4 shows a visualization of the contents of this implementation of a linked list. An “X” is used in place of an arrow that points to null.

      @@ -39155,12 +39120,12 @@
      Constructing a linked list
      linkedlistclasses
      -
      Figure 18.4 Visualization of linked list implementation with classes.
      +
      Figura 18.4 Visualization of linked list implementation with classes.

      Since we also increment the size field inside of LinkedList on each add, we know how many String objects it contains. Thus, we know how large of -an array to allocate in Program 18.6. The fillArray() method visits +an array to allocate in Programa 18.6. The fillArray() method visits every node in the linked list, storing its value into the allocated array. array. We sort the returned array and then print it as before.

      @@ -39183,13 +39148,13 @@
      Appending to the end of a linked references the tail of the list.

      -

      Program 18.7 adds a tail pointer called +

      Programa 18.7 adds a tail pointer called tail to the LinkedList class. Note that we have changed the add() method to the addFirst() method, and we have also added an addLast() method to make it easy to append elements to the end of a linked list.

      -
      Program 18.7 We can append to the end of a linked list by using an additional variable, tail, to reference the last element (tail) of the list.
      +
      Programa 18.7 We can append to the end of a linked list by using an additional variable, tail, to reference the last element (tail) of the list.
      public class LinkedListWithTail {
           private static class Node {
      @@ -39268,7 +39233,7 @@ 
      Inserting into a linked list
      the right point in the first place.

      -

      Program 18.8 is a version of a linked list that +

      Programa 18.8 is a version of a linked list that inserts elements into the linked list in sorted order. The only significant difference between it and the previous implementations of a linked list is its add() method. This method walks down the linked @@ -39279,7 +39244,7 @@

      Inserting into a linked list
      at the end.

      -
      Program 18.8 Linked list class in which calling the add() method inserts each value in sorted order.
      +
      Programa 18.8 Linked list class in which calling the add() method inserts each value in sorted order.
      public class SortedLinkedList {
           private static class Node {
      @@ -39469,7 +39434,7 @@ 

      18.4.2. Abstract Data Type: O these four methods.

      -
      Program 18.9 Interface specifying the stack ADT.
      +
      Programa 18.9 Interface specifying the stack ADT.
      public interface Stack {
           void push(String value);
      @@ -39484,10 +39449,10 @@ 
      Linked list implementation

      All the operations defined by the stack ADT (and interface) are implemented as methods in the class LinkedListStack, shown in -Program 18.10.

      +Programa 18.10.

      -
      Program 18.10 Class to implement a stack ADT using a linked list.
      +
      Programa 18.10 Class to implement a stack ADT using a linked list.
      public class LinkedListStack implements Stack {
           private static class Node {
      @@ -39566,12 +39531,12 @@ 
      Linked list implementation
      Dynamic array implementation
      -

      Like the dynamic array example of Program 18.3, -Program 18.11 implements a stack of String +

      Like the dynamic array example of Programa 18.3, +Programa 18.11 implements a stack of String values using a dynamic array data structure.

      -
      Program 18.11 Illustrates a stack ADT partially implemented using a dynamic array.
      +
      Programa 18.11 Illustrates a stack ADT partially implemented using a dynamic array.
      import java.util.Arrays;
       
      @@ -39621,12 +39586,12 @@ 
      Dynamic array implementation
      -
      Example 18.1 Postfix computation
      +
      Exemplo 18.1 Postfix computation

      At the beginning of the chapter, we introduced the problem of converting @@ -39665,7 +39630,7 @@

      Dynamic array implementation
      the same definition for TermStack given next.

      -
      Program 18.12 Class to manage a stack of Term objects.
      +
      Programa 18.12 Class to manage a stack of Term objects.
      public class TermStack {
           private static class Node {
      @@ -39710,7 +39675,7 @@ 
      Dynamic array implementation

      This class gives a linked list implementation of a stack. In fact, it’s -virtually identical to Program 18.10 with the +virtually identical to Programa 18.10 with the substitution of Term for String.

      @@ -39718,7 +39683,7 @@
      Dynamic array implementation
      short.

      -
      Program 18.13 Evaluates a postfix expression.
      +
      Programa 18.13 Evaluates a postfix expression.
      import java.util.*;
       
      @@ -39841,7 +39806,7 @@ 

      18.4.4. Abstract Data Type: O these four methods.

      -
      Program 18.14 Interface specifying the queue ADT.
      +
      Programa 18.14 Interface specifying the queue ADT.
      public interface Queue {
           void enqueue(String value);
      @@ -39854,7 +39819,7 @@ 

      18.4.4. Abstract Data Type: O
      Linked list implementation
      -

      Program 18.15 shows an implementation of the queue +

      Programa 18.15 shows an implementation of the queue ADT operations using a linked list. Because we need to keep track of nodes at both ends of the linked list, we maintain head and tail variables to reference these nodes. The enqueue() and dequeue() @@ -39862,7 +39827,7 @@

      Linked list implementation
      onto it and removed from it.

      -
      Program 18.15 Illustrates a queue ADT implemented using a linked list.
      +
      Programa 18.15 Illustrates a queue ADT implemented using a linked list.
      public class LinkedListQueue implements Queue {
           private static class Node {
      @@ -39927,7 +39892,7 @@ 

      18.5. Advanced: Generic data structur

      Most of the dynamic data structures we’ve seen in this chapter store values of type String. We’ve explored dynamic arrays of String values, linked lists of String objects, queues of String objects, and stacks -of String objects. In Example 18.1, we +of String objects. In Exemplo 18.1, we created the stack class TermStack to hold Term objects, but TermStack is identical to the existing LinkedListStack class with the substitution of Term for String.

      @@ -39937,7 +39902,7 @@

      18.5. Advanced: Generic data structur structures? What if you wanted a stack of int values or a queue of Thread objects? You might think that you need to create a distinct but similar implementation of each ADT for each type, as we do in -Example 18.1.

      +Exemplo 18.1.

      One possible solution is to take advantage of the fact that a variable @@ -39945,11 +39910,11 @@

      18.5. Advanced: Generic data structur since all classes are subtypes of Object. If we create data structures using Object as the underlying type, we can store values of any type in the data structure. For example, -Program 18.16 is an implementation of a stack ADT with +Programa 18.16 is an implementation of a stack ADT with an underlying data type of Object.

      -
      Program 18.16 Class that implements a stack of Object references.
      +
      Programa 18.16 Class that implements a stack of Object references.
      public class ObjectStack {
           private static class Node {
      @@ -40037,7 +40002,7 @@ 

      18.5.1. Generics in Java

      the need for run-time casting. A generic class is a class that gives a template for creating classes in which a placeholder for an underlying data type can be filled in when a specific instance of that class is -created. In the case of Example 18.1, we need +created. In the case of Exemplo 18.1, we need a stack that can hold Term objects instead of String objects, and a generic class would allow us to create a stack of any reference type.

      @@ -40126,16 +40091,16 @@

      18.5.1. Generics in Java

      The next two examples illustrate defining generic classes in Java.

      -
      Example 18.2 Defining a generic linked list
      +
      Exemplo 18.2 Defining a generic linked list
      -

      Program 18.17 defines a generic version of the +

      Programa 18.17 defines a generic version of the LinkedList class shown earlier. Note that it’s necessary to include the type parameter T on the outer class as well as the nested class Node.

      -
      Program 18.17 Class that implements a generic linked list.
      +
      Programa 18.17 Class that implements a generic linked list.
      public class GenericLinkedList<T> {
           private static class Node<T> {
      @@ -40170,7 +40135,7 @@ 

      18.5.1. Generics in Java

      -

      This class is almost indistinguishable from Program 18.5 except that +

      This class is almost indistinguishable from Programa 18.5 except that is uses type T instead of String.

      @@ -40193,12 +40158,12 @@

      18.5.2. Using a Generic Class

      new GenericClass<String>().

      -

      Program 18.18 uses the generic class +

      Programa 18.18 uses the generic class GenericLinkedList parameterized by String to re-implement -Program 18.6.

      +Programa 18.6.

      -
      Program 18.18 Uses the generic class GenericLinkedList to create and use a linked list of Strings.
      +
      Programa 18.18 Uses the generic class GenericLinkedList to create and use a linked list of Strings.
      import java.util.Arrays;
       import java.util.Scanner;
      @@ -40270,7 +40235,7 @@ 

      18.5.3. Using Java Libraries

      used as targets of enhanced for loops.

      -
      Example 18.3 Vectors
      +
      Exemplo 18.3 Vectors

      A Vector (java.util.Vector) implements an array of objects that can @@ -40284,14 +40249,14 @@

      18.5.3. Using Java Libraries

      method.

      -

      Program 18.19 illustrates a use of the Vector +

      Programa 18.19 illustrates a use of the Vector class. The program creates an empty Vector and generates random integers between 1 and 10, appending them to the end of the vector, until their sum is at least 100. Then, it prints the integers, their sum, and how many were generated.

      -
      Program 18.19 Illustrates the use of the Vector class.
      +
      Programa 18.19 Illustrates the use of the Vector class.
      import java.util.Random;
       import java.util.Vector;
      @@ -40317,7 +40282,7 @@ 

      18.5.3. Using Java Libraries

      -

      Output from a typical run of Program 18.19 is shown +

      Output from a typical run of Programa 18.19 is shown below:

      @@ -40343,7 +40308,7 @@

      18.5.3. Using Java Libraries

      -
      Example 18.4 Maps
      +
      Exemplo 18.4 Maps

      The HashMap(java.util.HashMap) is a very useful, general-purpose @@ -40353,7 +40318,7 @@

      18.5.3. Using Java Libraries

      arbitrary Java classes.

      -

      Program 18.20 reads a sequence of lines containing +

      Programa 18.20 reads a sequence of lines containing names and ages. For simplicity, each name is one word, and each age is a simple integer. It stores these (name, age) pairs in a HashMap<String,Integer> data structure. Once all the input is read and @@ -40362,7 +40327,7 @@

      18.5.3. Using Java Libraries

      ages of each person in the input file.

      -
      Program 18.20 Illustrates using a HashMap dictionary to store a mapping from names to ages.
      +
      Programa 18.20 Illustrates using a HashMap dictionary to store a mapping from names to ages.
      import java.util.HashMap;
       import java.util.Map;
      @@ -40443,7 +40408,7 @@ 

      18.5.3. Using Java Libraries

      18.6. Solution: Infix conversion

      Here we give our solution to the infix conversion problem from the -beginning of the chapter. As in Example 18.1, +beginning of the chapter. As in Exemplo 18.1, we use a stack of Term objects to solve the problem. However, we expand the Term class to hold both operands and operators. We only add methods and fields to the earlier definition, taking nothing away. In @@ -40536,7 +40501,7 @@

      18.6. Solution: Infix conversion

      With this updated Term class, we can create Term objects that hold either an operator or an operand and allow the precedence of operators to be compared. We use exactly the same TermStack class from -Example 18.1 for our stack. All that remains +Exemplo 18.1 for our stack. All that remains is the client code that parses the input.

      @@ -40649,7 +40614,7 @@

      18.6. Solution: Infix conversion

      The output from this program could be used as the input to the postfix -evaluator program from Example 18.1. A more complex program +evaluator program from Exemplo 18.1. A more complex program that did both the conversion and the calculation might want to store everything in a queue of Term objects instead of producing String output and then recreating Term objects.

      @@ -40666,12 +40631,12 @@

      18.7. Concurrency: Linked l can produce unexpected results.

      -

      Program 18.21 is a simple multi-threaded +

      Programa 18.21 is a simple multi-threaded program to test (and break!) the thread safety of the queue -implementation in Program 18.15.

      +implementation in Programa 18.15.

      -
      Program 18.21 Tests the queue implementation, including its thread safety.
      +
      Programa 18.21 Tests the queue implementation, including its thread safety.
      public class UseLinkedListQueue extends Thread {
           private static final int THREADS = 10;
      @@ -40799,7 +40764,7 @@ 

      18.7. Concurrency: Linked l

      How does this implementation fail? Consider the situation in which two threads are attempting to put a value in the queue simultaneously by calling -the enqueue() method in Program 18.15. Suppose +the enqueue() method in Programa 18.15. Suppose the first thread tests the queue and finds it empty (isEmpty() returns true) but is then interrupted. If a second thread gets control, it will also see that the queue’s empty, set the head and tail @@ -40831,7 +40796,7 @@

      18.7. Concurrency: Linked l method is called anyway.

      -
      Program 18.22 Synchronized version of the queue class that allows thread-safe use.
      +
      Programa 18.22 Synchronized version of the queue class that allows thread-safe use.
      public class LinkedListQueueSafe implements Queue {
           private static class Node {
      @@ -40883,7 +40848,7 @@ 

      18.7. Concurrency: Linked l

      With both enqueue() and dequeue() methods synchronized as in -Program 18.22, a typical output generated by the +Programa 18.22, a typical output generated by the program is shown below.

      @@ -40926,7 +40891,7 @@

      18.8. Concurrency: Thread-safe libra basic operations in Java that are needed to implement a set, list, or queue of items. The Map interface gives the basic operations for a dictionary, a collection of key-value pairs, one implementation of which -is the HashMap from Example 18.4.

      +is the HashMap from Exemplo 18.4.

      As we mentioned in Chapter 10, an interface can’t @@ -40936,7 +40901,7 @@

      18.8. Concurrency: Thread-safe libra carefully in order to know if a container is thread safe and react accordingly.

      -
      Example 18.5 ArrayList
      +
      Exemplo 18.5 ArrayList

      An ArrayList is like a Vector, with essentially the same interface @@ -40946,11 +40911,11 @@

      18.8. Concurrency: Thread-safe libra incorrect.

      -

      Program 18.23 is an example of synchronizing updates to the +

      Programa 18.23 is an example of synchronizing updates to the ArrayList class with multiple threads.

      -
      Program 18.23 Example of thread-safe use of an ArrayList.
      +
      Programa 18.23 Example of thread-safe use of an ArrayList.
      import java.util.ArrayList;
       
      @@ -41111,7 +41076,7 @@ 

      18.8. Concurrency: Thread-safe libra @@ -41133,22 +41098,22 @@

      18.9. Exercises

    2. On which line in -Program 18.1 is an exception generated? Why?

      +Programa 18.1 is an exception generated? Why?

    3. In -Program 18.2, is it possible to post-increment +Programa 18.2, is it possible to post-increment count inside the try clause rather than at the bottom of the while loop?

    4. Explain why the array inside the names -object in Program 18.4 is, on average, only three-quarters +object in Programa 18.4 is, on average, only three-quarters full.

    5. Based on the stack implementation in -Program 18.10, draw a picture of the linked list +Programa 18.10, draw a picture of the linked list structure after each of the following statements.

      @@ -41166,11 +41131,11 @@

      18.9. Exercises

    6. Implement the methods top() and isEmpty() for the dynamic array implementation of the stack in -Program 18.11.

      +Programa 18.11.

    7. Based on queue implementation in -Program 18.15, draw a picture of the linked list +Programa 18.15, draw a picture of the linked list structure after each of the following statements.

      @@ -41194,13 +41159,13 @@

      18.9. Exercises

      1. Implement a version of -DynamicArray from Program 18.3 that shrinks the size of its +DynamicArray from Programa 18.3 that shrinks the size of its internal storage array to half its size when only one quarter of its capacity is being used. This design can save significant amounts of space if a large number of items are added to the dynamic array at once and then removed.

      2. -

        Consider Program 18.7 which defines the +

        Consider Programa 18.7 which defines the LinkedListWithTail class for storing a linked list of String values. Add a reverse() method to the class which reverses the order of the nodes in the linked list. The key idea is make a new linked list @@ -41234,7 +41199,7 @@

        18.9. Exercises

      3. Create JUnit test cases to verify that the synchronized keywords are needed on the set() and -sort() methods of the DynamicArray example from Program 18.3. +sort() methods of the DynamicArray example from Programa 18.3. To test the set() method, you can create one thread that repeatedly sets, gets, and tests a changing value at a fixed location (e.g., 0) and another thread that continuously appends to the array (causing it to grow by copy @@ -41332,7 +41297,7 @@

        19.1. Problem: Maze of doom

        maze
        -
        Figure 19.1 Example of a maze to solve.
        +
        Figura 19.1 Example of a maze to solve.

      Finding a path through a maze involves systematically exploring twists @@ -41426,7 +41391,7 @@

      19.2.1. What is recursion?

      trees
      -
      Figure 19.2 Recursive refinement generating a tree-like image.
      +
      Figura 19.2 Recursive refinement generating a tree-like image.

      A recursive definition for your age suggests that recursion is all around @@ -41436,7 +41401,7 @@

      19.2.1. What is recursion?

      similar to the branching of its branches, which in turn is similar to the branching of its twigs. In fact, we borrow the idea of the branching of a tree to define a recursive data structure in -Section 19.4. Figure 19.2 +Section 19.4. Figura 19.2 starts with a simple Y-shaped branching. By successively replacing the branches with the previous shape, a tree is generated recursively. Fractals are images generated by similar recursive techniques. @@ -41461,7 +41426,7 @@

      19.2.2. Recursive definitions

      such as sn-1.

      -
      Example 19.1 Multiplication defined recursively
      +
      Exemplo 19.1 Multiplication defined recursively

      Even very common functions can be defined recursively. Consider the @@ -41487,12 +41452,12 @@

      19.2.2. Recursive definitions

      -
      Example 19.2 Factorial defined recursively
      +
      Exemplo 19.2 Factorial defined recursively

      Another mathematical function with a natural recursive definition is the @@ -41517,7 +41482,7 @@

      19.2.2. Recursive definitions

      -
      Example 19.3 Fibonacci defined recursively
      +
      Exemplo 19.3 Fibonacci defined recursively

      The Fibonacci sequence is an infinite sequence of integers starting with @@ -41653,7 +41618,7 @@

      19.2.4. Call stack

      parameters or returning values.

      -

      Figure 19.3 shows the stack frames being pushed +

      Figura 19.3 shows the stack frames being pushed onto the call stack as the main() method calls the factorial() method, starting with the argument 4. The factorial() method recursively calls itself with successively smaller values.

      @@ -41662,10 +41627,10 @@

      19.2.4. Call stack

      recursivecalls
      -
      Figure 19.3 Successive recursive method calls getting added to the call stack.
      +
      Figura 19.3 Successive recursive method calls getting added to the call stack.
      -

      Figure 19.4 shows the stack frames popping off +

      Figura 19.4 shows the stack frames popping off the call stack as each call to factorial() returns. As the answers are returned, they’re incorporated into the answer that’s generated and returned to the next caller in the sequence until the final answer 24 @@ -41675,7 +41640,7 @@

      19.2.4. Call stack

      recursivereturns
      -
      Figure 19.4 Recursive methods returning results to their callers.
      +
      Figura 19.4 Recursive methods returning results to their callers.
      @@ -41747,7 +41712,7 @@

      19.3. Syntax: Recursive methods

      to processing data structures.

      -
      Example 19.4 Factorial implemented recursively
      +
      Exemplo 19.4 Factorial implemented recursively

      In our first example of a recursive implementation, we return to the @@ -41782,7 +41747,7 @@

      19.3. Syntax: Recursive methods

      -
      Example 19.5 Fibonacci implemented recursively
      +
      Exemplo 19.5 Fibonacci implemented recursively

      Let’s return to the recursive definition of Fibonacci.

      @@ -41813,7 +41778,7 @@

      19.3. Syntax: Recursive methods

      @@ -41853,13 +41818,13 @@

      19.3. Syntax: Recursive methods

      -
      Example 19.6 Tower of Hanoi
      +
      Exemplo 19.6 Tower of Hanoi

      The famous Tower of Hanoi puzzle is another example commonly used to @@ -41867,7 +41832,7 @@

      19.3. Syntax: Recursive methods

      number of different sized disks. The puzzle begins with all disks arranged in a tower on one pole in decreasing size, with the smallest diameter disk on top and the largest on the bottom. -Figure 19.5 shows an example of the puzzle. The goal is to +Figura 19.5 shows an example of the puzzle. The goal is to move all the disks from the initial pole to the final pole, with two restrictions.

      @@ -41885,7 +41850,7 @@

      19.3. Syntax: Recursive methods

      hanoi
      -
      Figure 19.5 Tower of Hanoi puzzle with 4 disks on the initial pole.
      +
      Figura 19.5 Tower of Hanoi puzzle with 4 disks on the initial pole.

      The extra pole is used as a holder for intermediate moves. The idea @@ -41912,7 +41877,7 @@

      19.3. Syntax: Recursive methods

      The Tower of Hanoi solution in Java translates this outline into code.

      -
      Program 19.1 Recursive solution to the Tower of Hanoi with four disks and poles named 'A', 'B', and 'C'.
      +
      Programa 19.1 Recursive solution to the Tower of Hanoi with four disks and poles named 'A', 'B', and 'C'.
      public class TowerOfHanoi {
           public static void main(String[] args) {
      @@ -41942,7 +41907,7 @@ 

      19.3. Syntax: Recursive methods

      -
      Example 19.7 Exponentiation
      +
      Exemplo 19.7 Exponentiation

      Both Fibonacci and the Tower of Hanoi have natural recursive structures. @@ -42059,7 +42024,7 @@

      19.3. Syntax: Recursive methods

      @@ -42104,7 +42069,7 @@

      19.4. Syntax: Recursive data structur @@ -42116,7 +42081,7 @@

      19.4. Syntax: Recursive data structur example of merge sort.

      -
      Example 19.8 Merge sort
      +
      Exemplo 19.8 Merge sort

      Merge sort is an efficient sorting algorithm that’s often implemented @@ -42208,7 +42173,7 @@

      19.4. Syntax: Recursive data structur @@ -42249,19 +42214,19 @@

      19.4. Syntax: Recursive data structur manipulate recursive data structures.

      -
      Example 19.9 Recursive linked list size
      +
      Exemplo 19.9 Recursive linked list size

      How would you get the size of a linked list? The implementation in -Program 18.5 keeps track of its size as it grows, but +Programa 18.5 keeps track of its size as it grows, but what if it didn’t? A standard way to count the elements in the list would be to start with a reference to the head of the list and a counter with value zero. As long as the reference is not null, add one to the counter and set the reference to the next element on the list. -Program 19.2 counts the elements in this way.

      +Programa 19.2 counts the elements in this way.

      -
      Program 19.2 Linked list implementation whose size() method counts its elements iteratively.
      +
      Programa 19.2 Linked list implementation whose size() method counts its elements iteratively.
      public class IterativeListSize {
           private static class Node {
      @@ -42298,7 +42263,7 @@ 

      19.4. Syntax: Recursive data structur list.

      -

      Program 19.3 counts the elements in a linked +

      Programa 19.3 counts the elements in a linked list using this recursive procedure. Note that there’s a non-recursive size() method that calls the recursive size() method. This non-recursive method is called a proxy method. The recursive method @@ -42308,7 +42273,7 @@

      19.4. Syntax: Recursive data structur internals.

      -
      Program 19.3 Linked list implementation with a recursive size() method for counting its elements.
      +
      Programa 19.3 Linked list implementation with a recursive size() method for counting its elements.
      public class RecursiveListSize {
           private static class Node {
      @@ -42344,8 +42309,8 @@ 

      19.4. Syntax: Recursive data structur @@ -42379,7 +42344,7 @@

      19.4.1. Trees

      -

      Figure 19.6 shows a visualization of a tree. In +

      Figura 19.6 shows a visualization of a tree. In nature, a tree has its root at the bottom and branches upward. Since the root is the starting point for a tree data structure, it’s almost always drawn at the top.

      @@ -42388,7 +42353,7 @@

      19.4.1. Trees

      treevisualization
      -
      Figure 19.6 Visualization of a tree. The root is shown in light red. The leaves are shown in blue. The interior nodes are show in light purple.
      +
      Figura 19.6 Visualization of a tree. The root is shown in light red. The leaves are shown in blue. The interior nodes are show in light purple.

      Abstractly, a tree is either empty (the base case) or contains @@ -42402,7 +42367,7 @@

      19.4.1. Trees

      @@ -42411,7 +42376,7 @@

      19.4.1. Trees

      which each node references at most two other trees.

      -
      Example 19.10 Binary search tree
      +
      Exemplo 19.10 Binary search tree

      A binary search tree is a further special case of a binary tree with the @@ -42442,7 +42407,7 @@

      19.4.1. Trees

      This example is a simple binary tree that can store a list of String -values and print them out in alphabetical order. Program 19.4 shows +values and print them out in alphabetical order. Programa 19.4 shows the Tree class that defines the fields and two public methods, add() and print(), that operate on the tree. Each is a proxy method that calls its private recursive version, which takes a reference to a Node @@ -42462,7 +42427,7 @@

      19.4.1. Trees

      -
      Program 19.4 Class that implements a simple binary search tree ADT for creating a sorted list of Strings values.
      +
      Programa 19.4 Class that implements a simple binary search tree ADT for creating a sorted list of Strings values.
      public class Tree {
           private static class Node {
      @@ -42559,7 +42524,7 @@ 

      19.4.1. Trees

      -

      Figure 19.7 shows a visualization of the contents of +

      Figura 19.7 shows a visualization of the contents of this implementation of a binary search tree. As with a linked list, an “X” is used in place of arrows that point to null.

      @@ -42567,24 +42532,24 @@

      19.4.1. Trees

      treeclasses
      -
      Figure 19.7 Visualization of a tree implementation with classes.
      +
      Figura 19.7 Visualization of a tree implementation with classes.

      With the power of a binary search tree, it takes virtually no code at all to store a list of String values and then print them out in sorted -order. Program 19.5 gives an example of this +order. Programa 19.5 gives an example of this process using a Tree object for storage.

      -
      Program 19.5 Reads String values, stores them in a binary search tree, and prints the results in sorted order.
      +
      Programa 19.5 Reads String values, stores them in a binary search tree, and prints the results in sorted order.
      import java.util.Scanner;
       
      @@ -42618,16 +42583,16 @@ 

      19.4.2. Generic dynamic dynamic data structures and recursive methods to process them.

      -
      Example 19.11 Binary search tree to hold integers
      +
      Exemplo 19.11 Binary search tree to hold integers
      -

      Consider Program 19.6, which implements a tree that +

      Consider Programa 19.6, which implements a tree that stores values of type Integer. Although it would be more efficient to store int values, we use the Integer wrapper class to ease our eventual transition into a parameterized generic type.

      -
      Program 19.6 Variant of Program 19.4 that stores Integer values instead of String values.
      +
      Programa 19.6 Variant of Programa 19.4 that stores Integer values instead of String values.
      public class IntegerTree {
           private static class Node {
      @@ -42682,10 +42647,10 @@ 

      19.4.2. Generic dynamic can reuse code across a wide range of applications.

      -
      Example 19.12 Defining a generic binary search tree
      +
      Exemplo 19.12 Defining a generic binary search tree
      -

      Program 19.7 defines a generic version of the Tree +

      Programa 19.7 defines a generic version of the Tree class. This example is complicated by the fact that we need to be able to compare the value we want to store with the value in each Node object. We can’t make a tree with any arbitrary type. Objects of the @@ -42697,7 +42662,7 @@

      19.4.2. Generic dynamic compile-time.

      -
      Program 19.7 Class that implements a generic tree.
      +
      Programa 19.7 Class that implements a generic tree.
      public class GenericTree<T extends Comparable<T>> {
           private class Node {
      @@ -42766,16 +42731,16 @@ 

      19.4.2. Generic dynamic

      -
      Example 19.13 Using a generic class
      +
      Exemplo 19.13 Using a generic class
      -

      Program 19.8 uses the generic tree class to +

      Programa 19.8 uses the generic tree class to create two kinds of trees, a tree of String objects and a tree of Integer objects. Java library implementations of binary search trees are available as the TreeSet and TreeMap classes.

      -
      Program 19.8 Creates two trees with different underlying types.
      +
      Programa 19.8 Creates two trees with different underlying types.
      import java.util.Random;
       import java.util.Scanner;
      @@ -43105,7 +43070,7 @@ 

      19.6. Concurrency: Futures

      100,000,000 integers concurrently.

      -
      Example 19.14 Using futures to sum square roots
      +
      Exemplo 19.14 Using futures to sum square roots

      To use futures to sum the square roots of integers, we first need a @@ -43300,7 +43265,7 @@

      19.7. Exercises

      1. -

        Example 19.1 +

        Exemplo 19.1 gave a mathematical recursive definition for xy. Give a similar recursive definition for x + y, assuming that y is a positive integer. The structure is similar to the recursion to determine your current age given @@ -43316,7 +43281,7 @@

        19.7. Exercises

      2. Consider the first (non-memoized) recursive version of the Fibonacci method given in -Example 19.5. How many times is +Exemplo 19.5. How many times is fibonacci() called with argument 1 to compute fibonacci(n)? Instrument your program and count the number of calls for n = 2, 3, 4, …​, 20.

        @@ -43336,7 +43301,7 @@

        19.7. Exercises

        1. -

          Exercise 8.11 +

          Exercício 8.11 from Chapter 8 challenges you to write a method to determine whether a String is a palindrome. Recall that a palindrome (if punctuation and spaces are ignored) can be described as an empty String or @@ -43363,7 +43328,7 @@

          19.7. Exercises

        2. The efficient implementation of -Fibonacci from Example 19.5 +Fibonacci from Exemplo 19.5 eliminates redundant computation through memoization, storing values in an array as they’re found. However, it’s possible to carry along the computations of the previous two Fibonacci numbers without the @@ -43395,7 +43360,7 @@

          19.7. Exercises

          Write an implementation of fast exponentiation that works for even and odd n. This implementation is exactly the same as the one given at the end of -Example 19.7 except when n is odd. +Exemplo 19.7 except when n is odd. Use the following recursive definition of exponentiation to guide your implementation.

          @@ -43405,7 +43370,7 @@

          19.7. Exercises

        3. -

          Example 19.5 shows +

          Exemplo 19.5 shows two implementations that can be used to find the nth Fibonacci number. With some knowledge of recurrence relations, it’s possible to show that there’s a closed-form equation that gives the nth Fibonacci number Fn where @@ -43419,7 +43384,7 @@

          19.7. Exercises

          Although this equation is a bit ugly, you can plug numbers into it to discover the value of Fn quickly, provided that you have an efficient way to raise values to the nth power. Use the recursive algorithm for fast exponentiation -from Exercise 19.7 to make an implementation that finds the +from Exercício 19.7 to make an implementation that finds the nth Fibonacci number very quickly.

        @@ -43431,7 +43396,7 @@

        19.7. Exercises

      3. -

        Example 19.9 shows a way to +

        Exemplo 19.9 shows a way to calculate the size of a linked list recursively. Add a recursive method called print() to the RecursiveListSize class that prints out the values in the linked list recursively, one value per line.

        @@ -43445,7 +43410,7 @@

        19.7. Exercises

      4. Create a recursive find() method (and a non-recursive proxy method to call it) for the Tree class given in -Program 19.4. Its operation is similar to the add() +Programa 19.4. Its operation is similar to the add() method. If the subtree it’s examining is empty (null), it should return false. If the value it’s looking for is at the root of the current subtree, it should return true. These are the two base cases. @@ -43463,7 +43428,7 @@

        19.7. Exercises

        Create a recursive getHeight() method (and a non-recursive proxy method to call it) for the Tree class given in -Program 19.4. The base case is an empty tree (a null +Programa 19.4. The base case is an empty tree (a null pointer), which has a height of -1. For the recursive case of a non-empty tree, its height is one more than the height of the larger of its two subtrees.

        @@ -43471,7 +43436,7 @@

        19.7. Exercises

      5. Create a Java interface that describes a tree ADT. -Modify the programs in Example 19.10 to implement this interface.

        +Modify the programs in Exemplo 19.10 to implement this interface.

      @@ -43491,9 +43456,9 @@

      19.7. Exercises

      of random int values with lengths 1,000, 10,000, 100,000, and 1,000,000. Make two additional copies of each array. Then, sort each of three copies of the array with the selection sort algorithm given in -Example 6.2, the bubble sort algorithm given in +Exemplo 6.2, the bubble sort algorithm given in Section 10.1, and the merge sort algorithm given in -Example 19.8, respectively. Use the System.nanoTime() method to time +Exemplo 19.8, respectively. Use the System.nanoTime() method to time each of the sorts. Note that both selection sort and bubble sort might take quite a while to sort an array of 1,000,000 elements.

      @@ -43519,7 +43484,7 @@

      19.7. Exercises

    8. -

      Exercise 6.9 from Chapter 6 explains how binary search can be used to search for a value in a sorted +

      Exercício 6.9 from Chapter 6 explains how binary search can be used to search for a value in a sorted array of values. The idea is to play a “high-low” game, first looking at the middle value. If the value is the one you’re looking for, you’re done. If it’s too high, look in the lower half of the array. If it’s @@ -43697,7 +43662,7 @@

      20.2.1. Non-volatile storage

      @@ -43775,7 +43740,7 @@

      20.2.3. Text files and binary files

      @@ -43951,8 +43916,8 @@

      20.3.2. Reading and writing text files< @@ -44108,7 +44073,7 @@

      20.3.3. Reading and writing binary fi @@ -44128,7 +44093,7 @@

      20.3.3. Reading and writing binary fi use them with our baseball data example, we need to define a new class.

    -
    Program 20.1 Serializable BaseballPlayer class.
    +
    Programa 20.1 Serializable BaseballPlayer class.
    import java.io.Serializable;
     
    @@ -44339,9 +44304,9 @@ 

    20.3.3. Reading and writing binary fi @@ -44444,7 +44409,7 @@

    20.3.4. Using JFileChooser

    Next, we’ll give a short example that uses a JFileChooser.

    -
    Example 20.1 Using JFileChooser
    +
    Exemplo 20.1 Using JFileChooser

    The short program below allows a user to select a file using @@ -44453,7 +44418,7 @@

    20.3.4. Using JFileChooser

    number of bytes of storage that the file uses.

    -
    Program 20.2 Tool to determine size of file selected with JFileChooser.
    +
    Programa 20.2 Tool to determine size of file selected with JFileChooser.
    import javax.swing.JFileChooser; (1)
     import javax.swing.filechooser.FileNameExtensionFilter;
    @@ -44516,13 +44481,13 @@ 

    20.3.4. Using JFileChooser

    in those cases as well.

    -

    Figure 20.1 shows the dialog displayed by this program.

    +

    Figura 20.1 shows the dialog displayed by this program.

    fileChooserFigure
    -
    Figure 20.1 JFileChooser showing an open dialog.
    +
    Figura 20.1 JFileChooser showing an open dialog.
    @@ -44546,7 +44511,7 @@

    20.3.4. Using JFileChooser

    20.4. Examples: File examples

    -
    Example 20.2 Directory listing
    +
    Exemplo 20.2 Directory listing

    Let’s return to the File class and look at another example of how to @@ -44558,7 +44523,7 @@

    20.4. Examples: File examples

    is a directory.

    -
    Program 20.3 Directory listing tool.
    +
    Programa 20.3 Directory listing tool.
    import java.io.*;
     import java.text.*;
    @@ -44631,7 +44596,7 @@ 

    20.4. Examples: File examples

    -
    Example 20.3 Radiuses stored in a file
    +
    Exemplo 20.3 Radiuses stored in a file

    Now, let’s look at a data processing application of files. Let’s assume @@ -44641,7 +44606,7 @@

    20.4. Examples: File examples

    formula Area = πr2, and write those areas to a file called areas.txt.

    -
    Program 20.4 Reads a list of radiuses from a text file and outputs their areas to another text file.
    +
    Programa 20.4 Reads a list of radiuses from a text file and outputs their areas to another text file.
    import java.io.*;
     import java.util.*;
    @@ -44751,7 +44716,7 @@ 

    20.4. Examples: File examples

    and write to a binary file called areas.bin.

    -
    Program 20.5 Reads a list of radiuses from a binary file and output their areas to another binary file.
    +
    Programa 20.5 Reads a list of radiuses from a binary file and output their areas to another binary file.
    import java.io.*;
     
    @@ -44811,7 +44776,7 @@ 

    20.4. Examples: File examples

    @@ -45011,10 +44976,10 @@

    20.5. Solution: A picture is worth 1,000 bytes

    @@ -45042,7 +45007,7 @@

    20.6. Concurrency: File I/O

    prints the odd ones.

    -
    Program 20.6 Spawns threads that print odd and even numbers to a file concurrently.
    +
    Programa 20.6 Spawns threads that print odd and even numbers to a file concurrently.
    import java.io.*;
     
    @@ -45249,25 +45214,25 @@ 

    20.7. Exercises

  • -

    Program 20.5 from -Example 20.3 computes the areas of circles whose radiuses are given +

    Programa 20.5 from +Exemplo 20.3 computes the areas of circles whose radiuses are given as double values stored in a binary file. Although we provided a sample text file, we didn’t show a sample binary file since the contents would look like gibberish. Write a program that reads a file filled with double values stored as text and writes those same values into another file, storing the double values in binary. Afterward, you should be able to convert our sample text file into a sample binary file that can be used with -Program 20.5.

    +Programa 20.5.

  • Re-implement the RLE bitmap compression program from -Section 20.5 using only FileInputStream and +Seção 20.5 using only FileInputStream and FileOutputStream for file input and output. In some ways, doing so is simpler since you only need byte input and output for this program.

  • Update the RLE bitmap compression program from -Section 20.5 to use JFileChooser to allow the +Seção 20.5 to use JFileChooser to allow the user to select a file with a GUI instead of using command-line arguments.

  • @@ -45301,12 +45266,12 @@

    20.7. Exercises

    input character by character, ending a word when any punctuation or other characters are reached. Store each word (with a count of the number of times you find it) in a binary search tree such as those -described in Example 19.10. Then, traverse the +described in Exemplo 19.10. Then, traverse the tree, printing all the words found (and the number of times found) to the screen in alphabetical order.

  • -

    Expand the program from Exercise 20.12 so that it +

    Expand the program from Exercício 20.12 so that it also prompts for a second file containing a dictionary in the form of a word list with one word on each line. Store the words from the dictionary in another binary search tree. Then, for each word in the @@ -45377,7 +45342,7 @@

    20.7. Exercises

    Reading single bytes using either FileInputStream or DataInputStream is slow. It’s much faster to read a block of bytes all at once. Re-implement the RLE bitmap compression program from -Section 20.5 using the int read(byte[] b) +Seção 20.5 using the int read(byte[] b) method from the DataInputStream class, which tries to fill the array b with as many byte values as it can. If there are enough bytes left in the file, the array will be filled completely. If the array is longer than the remaining @@ -45394,7 +45359,7 @@

    20.7. Exercises

  • Write the RLE bitmap compression program from -Section 20.5 in parallel so that a file +Seção 20.5 in parallel so that a file is evenly divided into as many pieces as you have threads, compressed, and then each compressed portion is output in the correct order. Compare the speed for 2, 4, and 8 threads to the sequential implementation. Are @@ -45456,8 +45421,8 @@

    21.1. Problem: Web server

    @@ -45633,8 +45598,8 @@

    21.2. Concepts: TCP/IP communication

    @@ -45668,7 +45633,7 @@

    21.3.1. Addresses

    @@ -45759,7 +45724,7 @@

    21.3.2. Sockets

    @@ -45824,7 +45789,7 @@

    21.3.3. Receiving and sending data

    not be sent immediately.

  • -
    Example 21.1 Simple client and server
    +
    Exemplo 21.1 Simple client and server

    Here’s an example of a piece of server code which listens on port 4321, @@ -45885,12 +45850,12 @@

    21.3.3. Receiving and sending data

    -
    Example 21.2 Chat client and server
    +
    Exemplo 21.2 Chat client and server

    Here we look at a more complicated example of network communication, a chat @@ -46144,7 +46109,7 @@

    21.3.3. Receiving and sending data

    @@ -46419,7 +46384,7 @@

    21.4. Solution: Web server

    @@ -46452,14 +46417,14 @@

    21.5. Concurrency: Networking

    -

    Even in Example 21.2, it was convenient to +

    Even in Exemplo 21.2, it was convenient to create two different threads, Sender and Receiver. We didn’t create them for speedup but simply because they were doing two different jobs. Since the Sender waits for the user to type a line and the Receiver @@ -46524,14 +46489,14 @@

    21.6. Exercises

    1. -

      In Example 21.1 a client +

      In Exemplo 21.1 a client sends 100 int values, and a server sums them. Rewrite these fragments to send and receive the int values in text rather than binary format. You will need to send whitespace between the values.

    2. Add a GUI based on JFrame for the chat -program given in Example 21.2. Use a (non-editable) +program given in Exemplo 21.2. Use a (non-editable) JTextArea to display the log of messages, including user name. Provide a JTextField for entering messages, a JButton for sending messages, and another JButton for closing the network @@ -46575,7 +46540,7 @@

      21.6. Exercises

    3. Consider the multi-threaded implementation of a web server from -Exercise 21.10. Can you design an +Exercício 21.10. Can you design an experiment to measure the average amount of time a client waits to receive the requested file? How does this time change from the single-threaded to the multi-threaded version? If the file size is larger, is @@ -46590,7 +46555,7 @@

      21.6. Exercises

    diff --git a/pt_br/index.adoc b/pt_br/index.adoc index 7a88f5f..4ef2235 100644 --- a/pt_br/index.adoc +++ b/pt_br/index.adoc @@ -8,7 +8,7 @@ Barry Wittman ; Tim Korb ; Aditya Mathur :icons: font :stem: latexmath :xrefstyle: short -:listing-caption: Listing +:listing-caption: Programa :google-analytics-account: G-VEDGKRPMMK ifdef::ebook-format[:leveloffset: -1] diff --git a/pt_br/index.html b/pt_br/index.html index 49337c3..62d4a8a 100644 --- a/pt_br/index.html +++ b/pt_br/index.html @@ -811,7 +811,7 @@

    Agradecimentos