Chapter 2 Values, Variables, and Types

Chapter 2 Values, Variables, and Types

14 Chapter 2 Values, Variables, and Types In this chapter we explore the primitive building blocks that are used to develop Java programs. We experiment with the following concepts within DrJava’s interactive environment: • numeric and nonnumeric values • variables • expressions Next chapter we use these primitive concepts to build more sophisticated, computation-rich objects. 2.1 Java Values in DrJava’s Interaction Pane The DrJava environment provides an Interactions pane that is convenient for experimenting with Java’s primitive types. When you select the Interactions tab in the lower window panel, you see Interactions Welcome to DrJava. Working directory is /Users/rick/java > The greater than (>) prompt indicates the Interactions interpreter is ready to receive input from the user. If you type the number four Interactions Welcome to DrJava. Working directory is /Users/rick/java > 4 4 > the value four is displayed, and the prompt reappears waiting for additional input. In these simulated Interactions panes the user’s input appears to the right of the prompt (>), and the response of the interpreter appears on a line without a prompt; this is exactly how it works in DrJava’s Interactions pane. Also, when the message 13 March 2008 Draft © 2008 Richard L. Halterman 2.1. JAVA VALUES IN DRJAVA’S INTERACTION PANE 15 Welcome to DrJava. Working directory is /Users/rick/java appears in the Interactions pane it means that this is a fresh session. In a fresh session any prior user interactions are forgotten. A fresh session is instituted in one of several ways: • A new interactive session is started when DrJava begins running. • When the user issues the “Reset interactions” command from the DrJava menu the session is reinitialized. • Compiling a Java source file within the Editor pane resets the Interactions pane. The number four is an integer value. Java supports a variety of numeric value types and several kinds of nonnumeric values as well. Like mathematical integers, Java integers represent whole numbers, both positive and negative: Interactions Welcome to DrJava. Working directory is /Users/rick/java > -93 -93 Unlike mathematical integers, however, Java’s integers have a limited range. Consider the following interactive session: Interactions Welcome to DrJava. Working directory is /Users/rick/java > 2147483646 2147483646 > 2147483647 2147483647 > 2147483648 NumberFormatException: For input string: "2147483648" at java.lang.NumberFormatException.forInputString(NumberFormat... at java.lang.Integer.parseInt(Integer.java:463) at java.lang.Integer.valueOf(Integer.java:553) 2,147,483,647 is the largest integer that can be represented by Java’s “normal” integer type. Java’s standard integer type is called int. This limited range is common among programming languages since each number is stored in a fixed amount of memory. Larger numbers require more storage in memory. In Java (as in many other languages), ints require four bytes (32 bits) of memory. 2,147,483,647 is the largest integer that can be stored in four bytes. In order to model the infinite set of mathematical integers an infinite amount of memory would be needed! As we will see later, Java supports an integer type with a greater range and also provides support for arbitrary-precision integers. Now try to enter numbers with decimal places: Interactions Welcome to DrJava. Working directory is /Users/rick/java > 3.14159 3.14159 > -0.0045 -0.0045 13 March 2008 Draft © 2008 Richard L. Halterman 2.1. JAVA VALUES IN DRJAVA’S INTERACTION PANE 16 These are not integers but are more like mathematical real numbers. The key here is “like.” The name of this decimal type is double, which stands for double-precision floating point number. The term floating point means that the decimal point can “float” so the number of digits behind the decimal point can vary. As the double-precision label implies, Java also supports single-precision floating point numbers. Just like with ints, doubles use a fixed amount of memory, in this case eight bytes per value. This means that both the range and precision of doubles is limited. The largest double is 1.7976931348623157 × 10308 the smallest positive double is 4.9 × 10−324 doubles can be both positive and negative, and maintain a minimum of 15 digits of precision. Java’s doubles are therefore only an approximation of mathematical real numbers. An irrational number like π cannot be represented exactly since π has an infinite number of digits. While integers can be represented exactly within the range of values, because of finite precision not all floating point values can be represented. Consider: Interactions Welcome to DrJava. Working directory is /Users/rick/java > 1.227835364547718468456 1.2278353645477185 The double type cannot store 22 decimal digits of precision, so the desired value is rounded to just 17 digits. Programmers must take care when performing complex calculations involving doubles to ensure that cumulative rounding errors do not lead to meaningless results. Scientific notation can be used: Interactions Welcome to DrJava. Working directory is /Users/rick/java > 6.023e23 6.023E23 The number to the left of the e (capital E can be used as well) is the mantissa, and the number to the right of the e is the exponent of 10. 6.023e23 thus stands for 6.023 × 1023. One type of nonnumeric value is the boolean type. It has only two values: true and false. These values must be typed in exactly, as Java is case sensitive (capitalization matters): Interactions Welcome to DrJava. Working directory is /Users/rick/java > true true > True Error: Undefined class ’True’ > TRUE Error: Undefined class ’TRUE’ > false false > False Error: Undefined class ’False’ > FALSE Error: Undefined class ’FALSE’ 13 March 2008 Draft © 2008 Richard L. Halterman 2.2. VARIABLES AND ASSIGNMENT 17 The word Boolean comes from George Boole, a mathematician that founded the algebra of mathematical logic. At first glance, the boolean type may appear rather limited and useless, but as we will see it is essential for building powerful programs. Java supports other primitive data types. A comprehensive list can be found in Table 2.1, but we will have little need for them until later. For the time being we will restrict our attention to ints, doubles, and booleans. Name Meaning Range Size byte byte −128... + 127 8 bits short short integer −32,768... + 32,767 16 bits char Unicode character 0... + 65,536 16 bits int integer −2,147,483,648... + 2,147,483,647 32 bits long long integer −9,223,372,036,854,775,808 64 bits ... + 9,223,372,036,854,775,807 float single-precision floating point ±3.4 × 10+38 ... ± 1.4 × 10−45 32 bits with at least 7 decimal digits of precision double double-precision floating point ±1.7 × 10+308 ... ± 4.9 × 10−324 64 bits with at least 15 decimal digits of precision boolean Boolean false or true 8 bits Table 2.1: Primitive data types One non-primitive type that is worth noting at this point is String. A string is a sequence of characters. In Java, string literals are enclosed within quotation marks: Interactions Welcome to DrJava. Working directory is /Users/rick/java > "This is a string" "This is a string" A string is an example of a Java object, and so it is not a primitive type. This means that strings have capabilities that exceed those of primitive types. Some of these capabilities will be explored later. 2.2 Variables and Assignment In algebra, variables are used to represent numbers. The same is true in Java, except Java variables also can represent values other than numbers. Interactions Welcome to DrJava. Working directory is /Users/rick/java > x = 5 5 > x 5 In an actual Java program the first two lines of the above interaction would be terminated with semicolons and be called statements. The semicolons can be used in the Interactions pane as well: 13 March 2008 Draft © 2008 Richard L. Halterman 2.2. VARIABLES AND ASSIGNMENT 18 Interactions Welcome to DrJava. Working directory is /Users/rick/java > x = 5; > x 5 Notice how the terminating semicolon suppresses the evaluation of the entered expression; consider: Interactions Welcome to DrJava. Working directory is /Users/rick/java > 100 100 > 100; > The statement x = 5; is called an assignment statement because it assigns a value to a variable. The = operator is called the assignment operator, and its meaning is different from equality in mathematics. In mathematics, = asserts that the expression on its left is equal to the expression on its right. In Java, = makes the variable on its left take on the value of the expression on its right. It is best to read x = 5 as “x is assigned the value 5,” or “x gets the value 5.” This distinction is important since in mathematics equality is symmetric: if x = 5, we know 5 = x. In Java, this symmetry does not exist: Interactions Welcome to DrJava. Working directory is /Users/rick/java > x = 5 5 > 5 = x Error: Bad left expression in assignment The command 5 = x attempts to reassign the value of the literal integer value 5, but this cannot be done because 5 is always 5 and cannot be changed. To further illustrate the point consider: Interactions Welcome to DrJava. Working directory is /Users/rick/java > x = 5; > x 5 > x = x + 1; > x 6 In mathematics no number satisfies the equation x = x + 1. In Java the statement x = x + 1 works as follows: • The expression to the right of the = operator, x + 1, is evaluated. The current value of x (5 in this case) is added to 1, and so the right-hand side of the = evaluates to 6. 13 March 2008 Draft © 2008 Richard L.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    12 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us