Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 ARITHMETIC OPERATORS Java provides many operators that are useful for manipulating data and performing arithmetic.

Similar presentations


Presentation on theme: "1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 ARITHMETIC OPERATORS Java provides many operators that are useful for manipulating data and performing arithmetic."— Presentation transcript:

1 1 Chapter 2 JAVA FUNDAMENTALS CONT’D

2 2 ARITHMETIC OPERATORS Java provides many operators that are useful for manipulating data and performing arithmetic operations. Operators can be classified as unary, binary, or ternary depending on the number of operands the operator requires. –Unary operators require a single operand. –Binary operators require two operands. –Ternary operators require three operands.

3 3 ARITHMETIC OPERATORS Negation Operator (–) The negation operator is a unary operator that negates the value of its operand. The second assignment statement in the segment below assigns the value –50 to that variable named angle2. Note that after this assignment, angle1 still has the value 50. angle1 = 50; angle2 = –angle1;

4 4 ARITHMETIC OPERATORS Addition Operator (+) The addition operator is a binary operator that returns the sum of its two operands. In the last statement of the segment below the value in amount is added to the value in bonus and the resulting value, , is stored in total. The variable amount will still have the value and bonus will have the value at the end of the segment. amount = ; bonus = ; total = amount + bonus;

5 5 ARITHMETIC OPERATORS Subtraction Operator(–) The subtraction operator is a binary operator that returns the result of subtracting its right operand from its left operand. The following statement subtracts the value 27 from 70 and stores the result (43) in number. number = 70 – 27;

6 6 ARITHMETIC OPERATORS Multiplication Operator (*) The multiplication operator is a binary operator that returns the product of its two operands. In the following segment the value in rate is multiplied by the value in time and the result, 121.5, is stored in distance. The values of rate and time are not changed by the multiplication operator. rate = 40.5; time = 3; distance = rate * time;

7 7 ARITHMETIC OPERATORS Division Operator (/) The division operator is a binary operator that returns the quotient of its left operand divided by its right operand. In the statement below 160 is divided by 2 and the resulting value, 80, is assigned to the variable x. x = 160 / 2;

8 8 ARITHMETIC OPERATORS Division Operator (/) If both operands of the division operator are integers the quotient is an integer. The fractional part is truncated. In the statement below, the expression 161 / 2 has the value 80. This is because both operands of the division operator are of type int. The.5 is discarded. The value 80 is assigned to x. x = 161 / 2;

9 9 ARITHMETIC OPERATORS Division Operator (/) If at least one of the operands of the division operator is a floating-point type the quotient is a floating-point type. In the segment below, the expression / 2 has the value This value is stored in x. The expression 12 / z has the value 4.8. This value is stored in y. double z = 2.5; x = / 2; y = 12 / z;

10 10 ARITHMETIC OPERATORS Division Operator (/) Problem: What is the data type of the result of players / maxPlayers in the statement below? teams = players / maxPlayers; Answer:

11 11 ARITHMETIC OPERATORS Modulus Operator(%) The modulus operator is a binary operator that returns the remainder of a division operation. We can use this operator to find the number of items left over after a division operation. The following statement divides 12 by 10 and stores the remainder of the division (2) in nextDigit. nextDigit = 12 % 10;

12 12 THE Math CLASS The pow Method Java does not have an exponent operator. To raise a number to a power we can use the pow method of the Math class. You can think of a method as a routine that performs a specific operation. The pow method takes two double arguments. Arguments are data values sent to a method. The pow method raises the value of the first argument to the power of the second argument and returns the result of this calculation as a value of type double.

13 13 THE Math CLASS The pow Method Suppose that we want to calculate the volume of a cube. The volume of a cube, v, is specified by the algebraic formula: v = s 3 where s is the length of the side of the cube. In our program, if we have the side length of the cube stored in a variable named side, and we have already declared a variable named volume to hold the calculated volume, we could specify this calculation as follows: volume = Math.pow(side, 3);

14 14 THE Math CLASS The pow Method volume = Math.pow(side, 3); Math.pow(side, 3) is a call to the pow method which is a member of the Math class. This call is an expression, the value of this expression is the double value returned by the method. In our case, this value is assigned to the variable volume. Make sure volume is declared as type double or you will get a syntax error. Suppose side has the value 3.3, the value returned by the method call and assigned to volume is

15 15 THE Math CLASS The pow Method The value returned by the pow method can be used anywhere a double value can be used. For example the algebraic expression j = y - (x + 2) 6 could be encoded in Java as: j = y - Math.pow(x + 2, 6);

16 16 THE Math CLASS The sqrt Method Java does not have a square root operator. We can use the sqrt method of the Math class to find the square root of a number. The sqrt method takes a double argument and returns the square root of the argument as a value of type double.

17 17 THE Math CLASS The sqrt Method For example the algebraic expression: Could be encoded in Java as: z = 4 * Math.sqrt(a + b);

18 18 OPERATOR PRECEDENCE & ASSOCIATIVITY An expression may consist of a literal value, a variable, or be a combination of operators and operands. The evaluation of some expressions like is straightforward. Others are not so straightforward, for instance / 4. The value of this expression depends on whether the subtraction or the division is performed first.

19 19 OPERATOR PRECEDENCE & ASSOCIATIVITY In Java, mathematical expressions are processed from left to right. When two operators share an operand, the operation specified by the operator with the highest precedence is performed first. *** See Table 2-8 and Appendix C of the text

20 20 OPERATOR PRECEDENCE & ASSOCIATIVITY Continued on the next slide

21 21 OPERATOR PRECEDENCE & ASSOCIATIVITY

22 22 OPERATOR PRECEDENCE & ASSOCIATIVITY Division has higher precedence than subtraction. In the expression below, the division, 8 / 4, is performed first, producing a quotient of 2. Then 2 is subtracted from 16 producing a result of / 4

23 23 OPERATOR PRECEDENCE & ASSOCIATIVITY If two operators sharing an operand have the same precedence, the operators work according to their associativity. Associativity is either left-to-right or right-to-left. For instance, if a multiplication and division operator share an operand these operations will be performed left-to-right since multiplication and division associate from left-to- right.

24 24 OPERATOR PRECEDENCE & ASSOCIATIVITY Problem: What is the value of the following expression? ____ * 4

25 25 OPERATOR PRECEDENCE & ASSOCIATIVITY Problem: What is the value of the following expression? ____ 17 – 7 % 4 * 2

26 26 OPERATOR PRECEDENCE & ASSOCIATIVITY Problem: What is the value of the following expression? ____ / * 2

27 27 GROUPING WITH PARENTHESES You may enclose an expression in parentheses to ensure that it is evaluated before other expressions that involve its operands. Example: x = 10 – (8 – 4); The value of the expression, 10 – (8 – 4), is 6. Without the parentheses, the expression is 10 – 8 – 4, in this expression 8 would have been subtracted from 10 first, resulting in a value of 2, and then 4 would have been subtracted from 2, to produce the value –2.

28 28 GROUPING WITH PARENTHESES Example: If you wanted to encode the following algebraic expression in Java: You could write: y = (4 * a * c – d) / (2 – b); Without the parentheses, the equation implemented would be:

29 29 COMBINED ASSIGNMENT OPERATORS In programs, it is quite common to get the current value of a variable, modify it, and then assign the resulting value back to the original variable. Example: x = x + 10; This statement specifies that the value 10 is to be added to the current contents of the variable x and the resulting value becomes the new contents of x. Effectively, this statement increases the value of the variable x by 10.

30 30 COMBINED ASSIGNMENT OPERATORS Java provides a shorthand way to write this statement using the combined assignment plus equals operator, +=. Instead of writing the statement: x = x + 10; We can write: x += 10; The (+=) operator adds the value of its right operand to the current value of its left operand and stores the result in the left operand.

31 31 COMBINED ASSIGNMENT OPERATORS The minus equals operator, –= subtracts the value of its right operand from the current value of its left operand and stores the result in the left operand. For example: balance = balance – withdrawals; Could be written: balance – = withdrawals;

32 32 COMBINED ASSIGNMENT OPERATORS The left operand of a combined assignment operator is used as both the left operand of the specified arithmetic operation and the storage location for the result of the operation. The left operand of a combined assignment operator must be a variable.

33 33 COMBINED ASSIGNMENT OPERATORS *** See Table 2-13 of the text for more about the combined assignment operators and their usage The times equal operator, *=, multiplies the value of its right operand by the current value of its left operand and stores the result in the left operand. The divide equal operator, /=, divides the current value of its left operand by the value of the right operand and stores the result in the left operand. The mod equal operator, %=, divides the current value of its left operand by the value of the right operand and stores the remainder of the division in the left operand.

34 34 COMBINED ASSIGNMENT OPERATORS The combined assignment operators have lower precedence than the arithmetic operators +, –, *, /, and %. *** See Appendix C of the text For example the statement: w /= b + 1; Is equivalent to: w = w / (b + 1);

35 35 COMBINED ASSIGNMENT OPERATORS Precedence & Associativity Continued on the next slide

36 36 COMBINED ASSIGNMENT OPERATORS Precedence & Associativity Here are the combined assignment operators.

37 37 CONVERSION BETWEEN PRIMITIVE DATA TYPES Java is a strongly typed language. The Java compiler checks that the values assigned to variables are of a type compatible with the variables data type.

38 38 CONVERSION BETWEEN PRIMITIVE DATA TYPES Example: The compiler rejects the assignment statement in the segment below, saying “possible loss of precision”. double g = 13.9; int z; z = g; The compiler will not allow this assignment, because the data type double can hold a larger value than a variable of type int can hold.

39 39 CONVERSION BETWEEN PRIMITIVE DATA TYPES In Java the numeric data types are ranked. One data type outranks another if it can hold a larger value. *** See Figure 2-6 of the text

40 40 CONVERSION BETWEEN PRIMITIVE DATA TYPES In general, Java does not automatically perform narrowing conversions. A narrowing conversion is a conversion “from” a higher-ranking data type to a lower- ranking data type.

41 41 CONVERSION BETWEEN PRIMITIVE DATA TYPES double g = 13.9; int z; z = g; That is the problem with the assignment statement highlighted above. We are asking that a value of type double be stored in a variable of type int. This is a narrowing conversion - a compiler error occurs. It is an error to assign a double value to a variable of type int.

42 42 CONVERSION BETWEEN PRIMITIVE DATA TYPES Java automatically performs widening conversions. A widening conversion is a conversion “to” a higher- ranking data type.

43 43 CONVERSION BETWEEN PRIMITIVE DATA TYPES Example: The compiler automatically converts the value of type int to a value of type float in the assignment statement at the bottom of the segment below. This conversion is a widening conversion. (Remember an assignment does not change the right operand, the variable x still contains the 4-byte integer value 5 after the execution of the last statement.) int x = 5; float y; y = x; Here x is an int and y is a float. We are converting to a higher-ranking type. This is a widening conversion.

44 44 CONVERSION BETWEEN PRIMITIVE DATA TYPES The Cast Operator The cast operator is a unary operator that allows the programmer to convert a value to a different data type. You can specify either a narrowing or a widening conversion using the cast operator. The cast operator is a parenthesized data type. It specifies that the operand that follows is to be converted to the data type inside the parentheses.

45 45 CONVERSION BETWEEN PRIMITIVE DATA TYPES The Cast Operator When you convert a floating-point type to an integer type, any fractional portion is truncated (discarded). Note: The value is not rounded. The operand of the cast operator is not changed by the operation. A copy of the value is made that is of the specified data type.

46 46 CONVERSION BETWEEN PRIMITIVE DATA TYPES The Cast Operator Example: The third statement of the segment below specifies that the computer make a copy of the value in g that is of type int, then assign this integer value to the variable z. At the end of the segment z contains the value 13 and g still contains the double value double g = 13.9; int z; z = (int) g;

47 47 CONVERSION BETWEEN PRIMITIVE DATA TYPES The Cast Operator Example: The last statement of the following segment casts the value of the integer value stored in number to a char before assigning it to rating. Remember Java is strongly typed; it will not automatically convert the value of an integer variable to a char. The value in number is not changed by the cast, a copy of the value in number is made that is in Unicode. int number = 65; char rating; rating = (char) number;

48 48 CONVERSION BETWEEN PRIMITIVE DATA TYPES The Cast Operator Example: In the last statement of the segment below, a copy of the value in x is made that is of type double. This value, 22.0, is divided by the value in y, 8, the resulting value, 2.75, is assigned to g. Without the cast the result of the division would have been 2, an int. Java would have done a widening conversion and the value 2.0 would have been assigned to g. int x = 22, y = 8; double g; g = (double) x / y;

49 49 CONVERSION BETWEEN PRIMITIVE DATA TYPES The Cast Operator Problem: Describe the automatic type conversions that occur in the following segment. Assuming that the segment is part of a complete Java program, is the segment syntactically correct? float m = 4; double d = m; int j; j = Math.pow(2, 3); Answer:

50 50 CONVERSION BETWEEN PRIMITIVE DATA TYPES Automatic Type Conversion in Arithmetic Expressions When an arithmetic operator has operands of different data types, Java will temporarily convert the operand of the lower-ranking data type to the higher-ranking data type. The result of the operation will be the same data type as the higher-ranking operand. When values of type byte and short are used in arithmetic expressions, they are temporarily converted to type int.

51 51 CONVERSION BETWEEN PRIMITIVE DATA TYPES Automatic Type Conversion in Arithmetic Expressions Problem: Explain the type conversions made and give the values of all of the variables at the end of the execution of the following program segment. int x = 16, y = 8; short i = 5; float f = 2.2f, g = 0; double c = 0, d = 10.5; c = x / i; g = f * (x – 6) / y; x = (int) g; d = x y % 9 + c; Answer:

52 52 CREATING NAMED CONSTANTS USING THE KEY WORD final A named constant is a location in memory, which is given a name, that contains a data value that cannot be changed during the execution of the program. The declaration of a named constant looks like the declaration of a variable, except the key word final precedes the data type in the declaration of a constant. Example: final double SALES_TAX_RATE =.0825;

53 53 CREATING NAMED CONSTANTS USING THE KEY WORD final A named constant is a way of representing a literal value. Instead of using the literal value in expressions, we use the named constant. Named constants are used to make programs more readable and to facilitate the modification of programs. Examples: final double RATE_PER_MILE =.50; final double BONUS_LEVEL = ; final double INTEREST_RATE =.05667; final int INCHES_PER_FOOT = 12; final double LBS_PER_KG = 2.20;

54 54 CREATING NAMED CONSTANTS USING THE KEY WORD final By convention, programmers use all uppercase letters and separate words using the underscore character when naming constants. This helps distinguish named constants from variable names. Examples: final double RATE_PER_MILE =.50; final double BONUS_LEVEL = ; final double INTEREST_RATE =.05667; final int INCHES_PER_FOOT = 12; final double LBS_PER_KG = 2.20;

55 55 CREATING NAMED CONSTANTS USING THE KEY WORD final A named constant must be given a value when it is declared. It is a syntax error to write a statement that attempts to change the value in a named constant after its declaration.

56 56 The Math.PI Named Constant The Math class, from the Java API, provides a named constant called PI, which we can use in our programs. This constant has the value , which is an approximation of the mathematical value π. Notice, PI is not a method, it is not followed by a parenthesized argument list like pow or println. Example: In our program AreaOf2Circles.java, we could have used the following statement to calculate the area of a circle. area = Math.PI * Math.pow(radius, 2.0);

57 57 SCOPE The scope of a variable is the part of the program where the variable can be accessed by name. Variables declared inside a method are called local variables. The scope of a local variable begins at its declaration and ends at the closing brace, }, of the block in which it is defined. Variables cannot be accessed by statements outside this region. The compiler reads a program from top to bottom. The compiler must encounter the declaration of a variable before it finds the variable used in any other statement, or a syntax error occurs. You cannot declare two variables with the same name in the same scope.

58 58 COMMENTS Previously, we learned that comments are notes of explanation used to document programs, sections of programs, or program statements for the humans who must read programs.

59 59 COMMENTS In Java there are three ways to write comments. Single-Line comments begin with two forward slashes. The compiler ignores everything from the two forward slashes to the end of the line. Multi-Line comments start with a forward slash followed by an asterisk, /*, and are terminated by an asterisk followed by a forward slash, */. The compiler ignores everything between the /* and the */. This type of comment can span multiple lines. Documentation comments begin with a forward slash followed by two asterisks, /**, and end with an asterisk followed by a forward slash, */. The compiler ignores everything between the /** that marks the beginning of the comment and the */ then ends this comment. This type of comment is read by a program called javadoc.

60 60 COMMENTS Documentation Comments and javadoc The program javadoc is part of the Sun JDK. javadoc reads a source code file and creates an HTML file that includes the information provided in the documentation comments. The HTML file created by javadoc is formatted in the same way as the documentation provided for the Java API, so you can produce documentation for your classes that look just like standard Java documentation. Include a documentation comment before each class header, providing a description of the class. Include a documentation comment before each method header, which gives a description of the method.

61 61 PROGRAMMING STYLE Programming style is a way of using identifiers, spaces, tabs, blank lines, comments, and statements to make programs readable, simpler to understand, easier to maintain, and visually pleasing. When the compiler reads a program it processes it as one long stream of characters. The compiler doesn't care whether each statement is on a separate line or whether it all runs together. Good programmers follow programming style conventions to make their programming experience and that of their colleagues a positive and productive one.

62 62 PROGRAMMING STYLE *** Refer to the text and the document called Programming Style on webct

63 63 DIALOG BOXES A dialog box is a small graphical window that displays a message or requests input from the user. We can create dialog boxes using the JOptionPane class. Two types of boxes we can create using the JOptionPane class are: –Message Dialog - A dialog box that displays a message and an OK button. –Input Dialog - A dialog box that prompts the user for input, provides a text field where input is to be typed, and displays OK and Cancel buttons.

64 64 DIALOG BOXES In order to use the JOptionPane class we must include the following import statement in the source file before any class definition: import javax.swing.JOptionPane;

65 65 DIALOG BOXES The showMessageDialog Method of the JOptionPane Class The JOptionPane class has a static method called showMessageDialog, which we will use to display a message dialog. Here is a statement that calls the showMessageDialog method of the JOptionPane class to display the message dialog shown below: JOptionPane.showMessageDialog(null, "Go Stars!");

66 66 DIALOG BOXES The showMessageDialog Method of the JOptionPane Class JOptionPane.showMessageDialog(null, "Go Stars!"); The first argument specifies which frame the dialog is to be displayed in. In this class we will always specify the default frame by passing the key word null. The second argument is the message you want displayed in the dialog. The dialog box will close when the user clicks the OK button.

67 67 DIALOG BOXES The showInputDialog Method of the JOptionPane Class The JOptionPane class has a static method called showInputDialog, which we will use to display an input dialog. The second statement calls the showInputDialog method of the JOptionPane class to display the input dialog shown below: String enteredWeight; enteredWeight = JOptionPane.showInputDialog("Enter your " + "weight in pounds.");

68 68 DIALOG BOXES The showInputDialog Method of the JOptionPane Class enteredWeight = JOptionPane.showInputDialog("Enter your " + "weight in pounds."); The argument is the message you want displayed in the input dialog. This should be your prompt. If the user clicks the OK button, the variable enteredWeight will reference the String object that contains the string of characters entered by the user in the text field. If the user clicks the Cancel button, the String variable will reference a special value null.

69 69 DIALOG BOXES The showInputDialog Method of the JOptionPane Class String enteredWeight; enteredWeight = JOptionPane.showInputDialog("Enter your " + "weight in pounds."); The showInputDialog method of the JOptionPane class always returns the user’s input as a String. This is a problem if you wanted a numeric value that you could use in a mathematical expression. (You cannot do math on strings.) The method showInputDialog always returns a reference to a String object which it has created.

70 70 DIALOG BOXES Using a Method from a Java Wrapper Class to Convert a String to a Numeric Value To convert a String to numeric value, we can use a method from a Java wrapper class. Example: There is a class called Double that has a static member method called parseDouble, which converts a String to a double, and returns the double. We can use it as illustrated below: double weightInPounds; String enteredWeight; enteredWeight = JOptionPane.showInputDialog("Enter your " + "weight in pounds."); weightInPounds = Double.parseDouble(enteredWeight);

71 71 DIALOG BOXES Using a Method from a Java Wrapper Class to Convert a String to a Numeric Value double weightInPounds; String enteredWeight; enteredWeight = JOptionPane.showInputDialog("Enter your " + "weight in pounds."); weightInPounds = Double.parseDouble(enteredWeight); The argument of the parseDouble method is a reference to the string that is to be converted to a double. The string stored in the object referenced by enteredWeight is not changed by the parseDouble method. Pass the reference to the string that you want converted as the argument of the method.

72 72 DIALOG BOXES Using a Method from a Java Wrapper Class to Convert a String to a Numeric Value

73 73 DIALOG BOXES Using the System.exit Method to End the Program When you use the JOptionPane class to display dialogs in your program you must use the System.exit method to end the program, or a thread will continue to execute. System.exit(0); The argument, 0, is used to indicate that the program ended normally.

74 74 DIALOG BOXES *** See the program RectAreaUsingDialogs.java on webct


Download ppt "1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 ARITHMETIC OPERATORS Java provides many operators that are useful for manipulating data and performing arithmetic."

Similar presentations


Ads by Google