Download presentation

Presentation is loading. Please wait.

1
**Chapter 2 JAVA FUNDAMENTALS CONT’D**

1

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. 2

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; 3

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; 4

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; 5

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; 6

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; 7

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; 8

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 This value is stored in y. double z = 2.5; x = / 2; y = 12 / z; 9

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: 10

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; 11

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. 12

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 = s3 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); 13

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 14

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); 15

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. 16

17
**THE Math CLASS The sqrt Method**

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

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. 18

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 19

20
**OPERATOR PRECEDENCE & ASSOCIATIVITY**

Continued on the next slide 20

21
**OPERATOR PRECEDENCE & ASSOCIATIVITY**

21

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 14. / 4 22

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. 23

24
**OPERATOR PRECEDENCE & ASSOCIATIVITY**

Problem: What is the value of the following expression? ____ 2 + 3 * 4 24

25
**OPERATOR PRECEDENCE & ASSOCIATIVITY**

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

26
**OPERATOR PRECEDENCE & ASSOCIATIVITY**

Problem: What is the value of the following expression? ____ / * 2 26

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. 27

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: 28

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. 29

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. 30

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; 31

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. 32

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. 33

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); 34

35
**COMBINED ASSIGNMENT OPERATORS Precedence & Associativity**

Continued on the next slide 35

36
**COMBINED ASSIGNMENT OPERATORS Precedence & Associativity**

Here are the combined assignment operators. 36

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. 37

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. 38

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 39

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. 40

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. 41

42
**CONVERSION BETWEEN PRIMITIVE DATA TYPES**

Java automatically performs widening conversions. A widening conversion is a conversion “to” a higher-ranking data type. 42

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. 43

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. 44

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. 45

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 13.9. double g = 13.9; int z; z = (int) g; 46

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; 47

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; 48

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: 49

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. 50

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: 51

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; 52

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 = ; final int INCHES_PER_FOOT = 12; final double LBS_PER_KG = 2.20; 53

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 = ; final int INCHES_PER_FOOT = 12; final double LBS_PER_KG = 2.20; 54

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. 55

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); 56

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. 57

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. 58

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. 59

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. 60

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. 61

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

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. 63

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; 64

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!"); 65

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. 66

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."); 67

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. 68

69
**DIALOG BOXES The showInputDialog Method of the JOptionPane Class**

The method showInputDialog always returns a reference to a String object which it has created. 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.) 69

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); 70

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. 71

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

72

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. 73

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

Similar presentations

OK

1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.

1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google

Ppt on operating system concepts Ppt on hong kong tourism Ppt on regional trade agreements of china Ppt on zener diode Ppt on solar system with sound Ppt on eye os mean Ppt on human body systems Download ppt on the seven ages poem by william shakespeare Ppt on nature and history of democracy in nepal how to share Ppt on ill effects of intoxicating substances