Archive for July, 2007

Chapter 2 Introduction to Java Applications 79 The (Space web hosting)

Friday, July 27th, 2007

Chapter 2 Introduction to Java Applications 79 The circled numbers under the statement indicate the order in which Java applies the operators. The multiplication, modulus and division operations are evaluated first in left-toright order (i.e., they associate from left to right), because they have higher precedence than that of addition and subtraction. The addition and subtraction operations are evaluated next. These operations are also applied from left to right. Not all expressions with several pairs of parentheses contain nested parentheses. For example, the expression a * ( b + c ) + c * ( d + e ) does not contain nested parentheses. Rather, these parentheses are on the same level. To develop a better understanding of the rules of operator precedence, consider the evaluation of a second-degree polynomial (y = ax2 + bx + c): y = a * x * x + b * x + c; 16 2 4 3 5 The circled numbers under the preceding statement indicate the order in which Java applies the operators. There is no arithmetic operator for exponentiation in Java; x2 is represented as x*x. Suppose that a, b, c and x are initialized as follows: a=2, b=3, c=7 and x=5. Figure 2.18 illustrates the order in which the operators are applied in the preceding second- degree polynomial. As in algebra, it is acceptable to place unnecessary parentheses in an expression to make the expression clearer. Such unnecessary parentheses are also called redundant parentheses. For example, the preceding assignment statement might be parenthesized as follows: y = ( a * x * x ) + ( b * x ) + c; Good Programming Practice 2.16 Using parentheses for complex arithmetic expressions, even when the parentheses are not necessary, can make the arithmetic expressions easier to read. 2.8 Decision Making: Equality and Relational Operators This section introduces a simple version of Java s if structure that allows a program to make a decision based on the truth or falsity of some condition. If the condition is met (i.e., the condition is true), the statement in the body of the if structure is executed. If the condition is not met (i.e., the condition is false), the body statement does not execute. We will see an example shortly. Conditions in if structures can be formed by using the equality operators and relational operators summarized in Fig. 2.19. The relational operators all have the same level of precedence and associate from left to right. The equality operators both have the same level of precedence, which is lower than the precedence of the relational operators. The equality operators also associate from left to right. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

78 Introduction to Java Applications Chapter 2 Operator(s) (Yahoo web space)

Thursday, July 26th, 2007

78 Introduction to Java Applications Chapter 2 Operator(s) Operation(s) Order of evaluation (precedence) () Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right. *, /and % Multiplication Evaluated second. If there are several of this type of Division operator, they are evaluated from left to right. Modulus +or Addition Evaluated last. If there are several of this type of oper- Subtraction ator, they are evaluated from left to right. Fig. 2.17Precedence of arithmetic operators. g. 2.17 Now, let us consider several expressions in light of the rules of operator precedence. Each example lists an algebraic expression and its Java equivalent. The following is an example of an arithmetic mean (average) of five terms: abc++ de ++ Algebra: m = ————————————– 5 Java: m = ( a + b + c + d + e ) / 5; The parentheses are required, because division has higher precedence than that of addition. The entire quantity (a+b+c+d+e)is to be divided by 5. If the parentheses are erroneously omitted, we obtain a+b+c+d+e/5, which evaluates as abc ++ –e ++ d 5 The following is an example of the equation of a straight line: Algebra: y = mx + b Java: y = m * x + b; No parentheses are required. The multiplication operator is applied first, because multiplication has a higher precedence than that of addition. The assignment occurs last, because it has a lower precedence than that of multiplication and division. The following example contains modulus (%), multiplication, division, addition and subtraction operations: Algebra: z = + pr %qw /xy Java: z = p * r % q + w / x -y; 1 2 4 3 56 Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Jetty web server - Chapter 2 Introduction to Java Applications 77 Java

Thursday, July 26th, 2007

Chapter 2 Introduction to Java Applications 77 Java operation Arithmetic operator Algebraic expression Java expression Addition + f + 7 f + 7 Subtraction p c p -c Multiplication * bm b * m Division / x x / y x / yor –or x y y Modulus % r mod s r % s Fig. 2.16 Arithmetic operators. Arithmetic expressions in Java must be written in straight-line form to facilitate entering programs into the computer. Thus, expressions such as adivided by b must be written as a/b, so that all constants, variables and operators appear in a straight line. The following algebraic notation is generally not acceptable to compilers: a b Parentheses are used in Java expressions in the same manner as in algebraic expressions. For example, to multiply atimes the quantity b+c, we write a * ( b + c ) Java applies the operators in arithmetic expressions in a precise sequence determined by the following rules of operator precedence, which are generally the same as those followed in algebra: 1. Operators in expressions contained within pairs of parentheses are evaluated first. Thus, parentheses may be used to force the order of evaluation to occur in any sequence desired by the programmer. Parentheses are at the highest level of precedence. In cases of nested or embedded parentheses, the operators in the innermost pair of parentheses are applied first. 2. Multiplication, division and modulus operations are applied next. If an expression contains several multiplication, division or modulus operations, the operators are applied from left to right. Multiplication, division and modulus operators have the same level of precedence. 3. Addition and subtraction operations are applied last. If an expression contains several addition and subtraction operations, the operators are applied from left to right. Addition and subtraction operators have the same level of precedence. The rules of operator precedence enable Java to apply operators in the correct order. When we say that operators are applied from left to right, we are referring to the associativity of the operators. We will see that some operators associate from right to left. Figure 2.17 summarizes these rules of operator precedence. This table will be expanded as additional Java operators are introduced. A complete precedence chart is included in Appendix C. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

76 Introduction to Java Applications Chapter 2 number1 (Web hosting solutions)

Wednesday, July 25th, 2007

76 Introduction to Java Applications Chapter 2 number1 number2 45 72 Fig. 2.1414 Memory locations after storing values for number1and number2. Fig. After the program of Fig. 2.9 obtains values for number1and number2, it adds the values and places the sum into variable sum. The statement sum = number1 + number2; performs the addition and also replaces sum s previous value. After sum has been calculated, memory appears as shown in Fig. 2.15. Note that the values of number1 and number2 appear exactly as they did before they were used in the calculation of sum. These values were used, but not destroyed, as the computer performed the calculation. Thus, when a value is read from a memory location, the process is nondestructive. 2.7 Arithmetic Most programs perform arithmetic calculations. The arithmetic operators are summarized in Fig. 2.16. Note the use of various special symbols not used in algebra. The asterisk (*) indicates multiplication, and the percent sign (%) is the modulus operator, which is discussed shortly. The arithmetic operators in Fig. 2.16 are binary operators, because they each operate on two operands. For example, the expression sum+valuecontains the binary operator +and the two operands sumand value. Integer division yields an integer quotient; for example, the expression 7/4evaluates to 1, and the expression 17/5evaluates to 3. Note that any fractional part in integer division is simply discarded (i.e., truncated) no rounding occurs. Java provides the modulus operator, %, that yields the remainder after integer division. The expression x%yyields the remainder after xis divided by y. Thus, 7%4yields 3, and 17%5yields 2. This operator is most commonly used with integer operands, but also can be used with other arithmetic types. In later chapters, we consider many interesting applications of the modulus operator, such as determining if one number is a multiple of another. There is no arithmetic operator for exponentiation in Java. Chapter 5 shows how to perform exponentiation in Java. [Note: The modulus operator can be used with both integer and floating-point numbers.] number1 number2 sum 45 72 117 Fig. Fig. 2.15Memory locations after calculating the sum15 of number1and number2. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 2 Introduction to Java Applications 75 Message (Http web server)

Wednesday, July 25th, 2007

Chapter 2 Introduction to Java Applications 75 Message dialog type Icon Description JOptionPane.ERROR_MESSAGE Displays a dialog that indicates an error to the user. JOptionPane.INFORMATION_MESSAGE Displays a dialog with an informational message to the user. The user can sim ply dismiss the dialog. JOptionPane.WARNING_MESSAGE Displays a dialog that warns the user of a potential problem. JOptionPane.QUESTION_MESSAGE Displays a dialog that poses a question to the user. This dialog normally requires a response, such as clicking on a Yes or a No button. JOptionPane.PLAIN_MESSAGE no icon Displays a dialog that simply contains a message, with no icon. Fig. 2.12 JOptionPaneconstants for message dialogs. 2.6 Memory Concepts Variable names such as number1, number2and sumactually correspond to locations in the computer’s memory. Every variable has a name, a type, a size and a value. In the addition program of Fig. 2.9, when the statement number1 = Integer.parseInt( firstNumber ); executes, the string previously typed by the user in the input dialog and stored in first- Number is converted to an int and placed into a memory location to which the name number1has been assigned by the compiler. Suppose that the user enters the string 45as the value for firstNumber. The program converts firstNumber to an int, and the computer places that integer value, 45, into location number1, as shown in Fig. 2.13. Whenever a value is placed in a memory location, the value replaces the previous value in that location. The previous value is destroyed (i.e., lost). When the statement number2 = Integer.parseInt( secondNumber ); executes, suppose that the user enters the string 72as the value for secondNumber. The program converts secondNumberto an int, and the computer places that integer value, 72, into location number2. The memory appears as shown in Fig. 2.14. number1 45 Fig. 2.1313 Memory location showing the name and value of variable number1. Fig. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

74 Introduction to (Web hosting ecommerce) Java Applications Chapter 2 which

Tuesday, July 24th, 2007

74 Introduction to Java Applications Chapter 2 which uses the operator +to add a String(the literal “Thesumis “) and the value of variable sum(the intvariable containing the result of the addition on line 31). Java has a version of the +operator for string concatenation that concatenates a Stringand a value of another data type (including another String); the result of this operation is a new (and normally longer) String. If we assume that sumcontains the integer value 117, the expression evaluates as follows: 1. Java determines that the two operands of the + operator (the string “The sum is “and the integer sum) are of different types and one of them is a String. 2. Java converts sumto a String. 3. Java appends the Stringrepresentation of sumto the end of “Thesumis “, resulting in the String”Thesumis117″. Method showMessageDialog displays the resulting String in the dialog box. Note that the automatic conversion of integer sum occurs only because the addition operation concatenates the String literal “The sum is” and sum. Also, note that the space between isand 117is part of the string “Thesumis “. String concatenation is discussed in detail in Chapter 10, Strings and Characters. Common Programming Error 2.10 Confusing the +operator used for string concatenation with the +operator used for addition can lead to strange results. For example, assuming that integer variable yhas the value 5, the expression “y+2=”+y+2results in the string “y+2=52″, not “y+2=7″, because first the value of yis concatenated with the string “y+2=”, and then the value 2 is concatenated with the new larger string “y+2=5″. The expression “y+2=”+(y+ 2)produces the desired result. The third and fourth arguments of method showMessageDialogin Fig. 2.9 represent the string that should appear in the dialog box s title bar and the dialog box type, respectively. The fourth argument JOptionPane.PLAIN_MESSAGE is a value indicating the type of message dialog to display. This type of message dialog does not display an icon to the left of the message. Figure 2.11 illustrates the second and third arguments and shows that there is no icon in the window. The message dialog types are shown in Fig. 2.12. All message dialog types except PLAIN_MESSAGEdialogs display an icon to the user indicating the type of message. The user clicks OK to dismiss the dialog. Argument 2: The message to display Argument 3: The title bar string Fig. 2.111 Message dialog box customized with the four-argument version of Fig. method showMessageDialog. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 2 Introduction to Java Applications 73 Line (Make my own web site)

Tuesday, July 24th, 2007

Chapter 2 Introduction to Java Applications 73 Line 22 is a single-line comment indicating that the next statement reads the second number from the user. Lines 23 24, secondNumber = JOptionPane.showInputDialog( “Enter second integer” ); display an input dialog in which the user types a String representing the second of the two integers to add. Lines 27 28, number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); convert the two Strings input by the user to int values that the program can use in a calculation. Method Integer.parseInt(a static method of class Integer) converts its String argument to an integer. Class Integer is defined in package java.lang. Line 27 assigns the int (integer) value that Integer.parseInt returns to variable number1. Line 28 assigns the int (integer) value that Integer.parseInt returns to variable number2. Line 31, sum = number1 + number2; is an assignment statement that calculates the sum of the variables number1 and number2 and assigns the result to variable sum by using the assignment operator, =. The statement is read as, sumgets the value of number1+number2. Most calculations are performed in assignment statements. When the program encounters the addition operation, it uses the values stored in the variables number1 and number2 to perform the calculation. In the preceding statement, the addition operator is a binary operator: its two operands are number1 and number2. Good Programming Practice 2.15 Place spaces on either side of a binary operator. This format makes the operator stand out and makes the program more readable. After the calculation has been performed, lines 34 36, JOptionPane.showMessageDialog( null, “The sum is ” + sum, “Results”, JOptionPane.PLAIN_MESSAGE ); use method JOptionPane.showMessageDialog to display the result of the addition. This new version of JOptionPane method showMessageDialog requires four arguments. As in Fig. 2.6, the null first argument indicates that the message dialog will appear in the center of the screen. The second argument is the message to display. In this case, the second argument is the expression “The sum is ” + sum Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

72 Introduction to Java Applications Chapter 2 thus, (Web hosting reseller)

Monday, July 23rd, 2007

72 Introduction to Java Applications Chapter 2 thus, they must appear in all lowercase letters. Chapter 4 summarizes the eight primitive types (boolean, char, byte, short, int, long, floatand double). Line 18 is a single-line comment indicating that the next statement reads the first number from the user. Lines 19 20, firstNumber = JOptionPane.showInputDialog( “Enter first integer” ); reads from the user a String representing the first of the two integers to add. Method JOptionPane.showInputDialogdisplays the input dialog in Fig. 2.10. The argument to showInputDialogindicates what the user should type in the text field. This message is called a prompt, because it directs the user to take a specific action. The user types characters in the text field, and then clicks the OK button or presses the Enter key to return the string to the program. (If you type and nothing appears in the text field, position the mouse pointer in the text field and click the left mouse button to activate the text field.) Unfortunately, Java does not provide a simple form of input that is analogous to displaying output in the command window with System.out s method print and println. For this reason, we normally receive input from a user through a GUI component (an input dialog box in this program). Technically, the user can type anything in the text field of the input. Our program assumes that the user follows directions and enters a valid integer value. In this program, if the user either types a noninteger value or clicks the Cancel button in the input dialog, a runtime logic error will occur. Chapter 14, Exception Handling, discusses how to make your programs more robust by enabling them to handle such errors. This is also known as making your program fault tolerant. The result of JOptionPane method showInputDialog (a String containing the characters typed by the user) is given to variable firstNumberby using the assignment operator, =. The statement (lines 19 20) is read as firstNumber gets the value of JOptionPane.showInputDialog( “Enter first integer” ). The = operator is called a binary operator, because it has two operands: firstNumberand the result of the expression JOptionPane.showInputDialog( “Enter first integer”). This whole statement is called an assignment statement, because it assigns a value to a variable. The expression to the right side of the assignment operator, =, is always evaluated first. In this case, the program calls method showInputDialog, and the value input by the user is assigned to firstNumber. Prompt to the user. When the user clicks OK, showInputDialog returns the 45 typed by the user to the program as a String. The program must convert the Stringto an integer. Text field in which the user types a value. Fig. 2.10 Input dialog box. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 2 Introduction to Java Applications 71 are (Hosting your own web site)

Monday, July 23rd, 2007

Chapter 2 Introduction to Java Applications 71 are declarations. The words firstNumber and secondNumber are the names of variables. A variable is a location in the computer s memory where a value can be stored for use by a program. All variables must be declared with a name and a data type before they can be used in a program. This declaration specifies that the variables firstNumber and secondNumber are data of type String (located in package java.lang), which means that the variables will hold strings. A variable name can be any valid identifier. Like statements, declarations end with a semicolon (;). Notice the single-line comments at the end of each line. This use and placement of the comments is a common practice used by programmers to indicate the purpose of each variable in the program. Good Programming Practice 2.12 Choosing meaningful variable names helps a program to be self-documenting (i.e., it becomes easier to understand the program simply by reading it rather than by reading manuals or viewing an excessive number of comments). Good Programming Practice 2.13 By convention, variable-name identifiers begin with a lowercase letter. As with class names, every word in the name after the first word should begin with a capital letter. For example, identifier firstNumber has a capital Nin its second word, Number. Good Programming Practice 2.14 Some programmers prefer to declare each variable on a separate line. This format allows for easy insertion of a descriptive comment next to each declaration. Software Engineering Observation 2.2 Java automatically imports classes from package java.lang, such as class String. Therefore, import statements are not required for classes in package java.lang. Declarations can be split over several lines, with each variable in the declaration separated by a comma (i.e., a comma-separated list of variable names). Several variables of the same type may be declared in one declaration or in multiple declarations. Lines 12 13 can also be written as follows: String firstNumber, // first string entered by user secondNumber; // second string entered by user Lines 14 16, int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 declare that variables number1, number2 and sum are data of type int, which means that these variables will hold integer values (whole numbers such as 7, 11, 0 and 31,914). We will soon discuss the data types float and double, for specifying real numbers (numbers with decimal points, such as 3.4, 0.0 and 11.19), and variables of type char, for specifying character data. A char variable may hold only a single lowercase letter, a single uppercase letter, a single digit or a single special character (such as x, $, 7 and *) and escape sequences (such as the newline character, n). Java is capable of representing characters from many other spoken languages. Types such as int, double and char are often called primitive data types, or built-in data types. Primitive-type names are keywords; Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Free php web host - 70 Introduction to Java Applications Chapter 2 37

Monday, July 23rd, 2007

70 Introduction to Java Applications Chapter 2 37 38 System.exit( 0 ); // terminate application 39 40 } // end method main 41 42 } // end class Addition Fig. 2.9An addition program in action (part 2 of 2). Fig. 2. Lines 1 and 2, // Fig. 2.9: Addition.java // An addition program. are single-line comments stating the figure number, file name and purpose of the program. Line 4, // Java extension packages is a single-line comment specifying that the next line imports a class from the Java extension packages. Line 5, import javax.swing.JOptionPane; // import class JOptionPane indicates that the compiler should load class JOptionPanefor use in this application. As stated earlier, every Java program consists of at least one class definition. Line 7, public class Addition { begins the definition of class Addition. The file name for this public class must be Addition.java. Remember that all class definitions start with an opening left brace (at the end of line 7), {, and end with a closing right brace, }(in line 42). As stated earlier, every application begins execution with method main(lines 10 40). The left brace (line 11) marks the beginning of main s body and the corresponding right brace (line 36) marks the end of main s body. Lines 12 13, String firstNumber; // first string entered by user String secondNumber; // second string entered by user Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01