1 / 31

Chapter 2

Chapter 2. Data and Expressions Part Two. Outline. Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs. Expressions. An expression is a combination of one or more operators and operands

redford
Download Presentation

Chapter 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 2 Data and Expressions Part Two

  2. Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs

  3. Expressions • An expression is a combination of one or more operators and operands • Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder % • If either or both operands used by an arithmetic operator are floating point, then the result is a floating point

  4. Division and Remainder • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3equals 4 8 / 12equals 0 • The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % 3equals 2 8 % 12equals 8

  5. Arithmetic Expressions - continued • If operands are mixed, results are ‘promoted.’ • 4.5 + 2 = 6.5 (double) • Sometimes called “widened.”

  6. Operator Precedence • Operators can be combined into complex expressions result = total + count / max - offset; • Operators have a well-defined precedence which determines the order in which they are evaluated • Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation • Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order

  7. Operator Precedence • What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1

  8. + / a - d b c Expression Trees • The evaluation of a particular expression can be shown using an expression tree • The operators lower in the tree have higher precedence for that expression a + (b – c) / d

  9. Assignment Revisited • The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side Then the result is stored in the variable on the left hand side NOTE: the ‘assignment operator (again) IS an operator – (merely has lower precedence than arithmetic operators….)

  10. Assignment Revisited • The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value) KNOW THE OPERATOR PRECEDENCE TABLE ON PAGE 78. It will grow significantly!

  11. Increment and Decrement • The increment and decrement operators use only one operand • The increment operator (++) adds one to its operand • The decrement operator (--) subtracts one from its operand • The statement count++; is functionally equivalent to count = count + 1;

  12. Increment and Decrement • The increment and decrement operators can be applied in postfix form: count++ • or prefix form: ++count •  When used as part of a larger expression, the two forms can have different effects • Because of their subtleties, the increment and decrement operators should be used with care

  13. Assignment Operators • Often we perform an operation on a variable, and then store the result back into that variable • Java provides assignment operators to simplify that process • For example, the statement num += count; is equivalent to num = num + count;

  14. Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y Assignment Operators • There are many assignment operators in Java, including the following:

  15. Assignment Operators •  The right hand side of an assignment operator can be a complexexpression • The entireright-hand expression is evaluated first, then the result is combined with the original variable • Therefore result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num);

  16. Assignment Operators • The behavior of some assignment operators depends on the types of the operands • If the operands to the += operator are strings, the assignment operator performs string concatenation • The behavior of an assignment operator (+=) is always consistent with the behavior of the corresponding operator (+)

  17. Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs

  18. Data Conversion • Sometimes it is convenient to convert data from one type to another • For example, in a particular situation we may want to treat an integer as a floating point value • These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation

  19. Data Conversion • Conversions must be handled carefully to avoid losing information • Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) • Narrowing conversions can loseinformation because they tend to go from a large data type to a smaller one (such as an int to a short) • In Java, data conversions can occur in three ways: • assignment conversion • promotion • casting

  20. Assignment Conversion • Assignment conversion occurs when a value of one type is assigned to a variable of another • If money is a float variable and dollars is an int variable, the following assignment converts the value in dollars to a float money = dollars • Only widening conversions can happen via assignment (I do NOT believe this to be true!) • Note that the value or type of dollars did not change

  21. Data Conversion • Promotion happens automatically when operators in expressions convert their operands • For example, • if sum is a float and count is an int, • the value of count is converted to a floating point value to perform the following calculation: result = sum / count; • Result is stored in result. • BUT count is still an int. It was promoted in order only to evaluate this expression, but it is still an int.

  22. Casting • Casting is the most powerful, and dangerous, technique for conversion (but done all the time) • To cast, the type is put in parentheses in front of the value being converted • For example, if total and count are both integers, but we want a floating point result when dividing them, we can cast total: (This makes one of the operands a float; this forces count to be promoted to float for the division to take place. • Remember, both total and count remain ints after. result = (float) total / count;

  23. Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs

  24. The Scanner Class • The Scanner class is part of the standard Java class library and makes elementary input/output easier for new Java students. • We will use it for now. • Scanner objects allow us to input data either interactively (from the keyboard) or from a data file. • Scanner methods also allow us to parse a String into its constituent components. • Of course, to use any methods of a class, we must instantiate the class and create an object of that class.

  25. Scanner Object Methods String next() method returns the next input token as a char string String nextLine() method returns all input remaining on current line as a single character string byte nextByte() returns the next byte double nextDouble() returns the next double float nextFloat() returns the next float int nextInt() returns the next int. A number of additional methods are available…. Look and see!  Discuss methods and how they become available from this object!

  26. Scanner Objects • Create Scanner objects: Scanner scan = new Scanner (System.in); This creates a new object called ‘scan’ and tells the object that the input will be coming from the system standard input stream (defaults to keyboard). The object is created by the ‘new’ operator, which calls a special method called a ‘constructor’ to set up the object. The constructor takes the System.in as an argument and now looks for input to come via the keyboard.

  27. Scanner Objects • Inputs: Scanner object assumes input ‘tokens’ are separated by a ‘delimiter.’ • Default delimiter is ‘white space’ (blanks or a few special characters – later). • Delimiters can be changed to, say, commas, … • Delimiters are used to separate the inputs from each other.

  28. Scanner Example import java.util.Scanner; public class GasMileage { // Program computes gas mileage given input miles and gasoline consumed public static void main (String [ ] args) { int miles; double gallons, mpg; Scanner scan = new Scanner (System.in); System.out.println (“Enter the number of miles as an integer: “); miles = scan.nextInt(); System.out.println (“Enter the number of gallons of fuel used as a decimal: “); gallons = scan.nextDouble(); mpg = miles/gallons; System.out.println (“Miles Per Gallon: “ + mpg); }// end main() }// end class GasMileage

  29. Sample Outputs: Enter the number of miles: 328 Enter the gallons of fuel used: 11.2 Miles Per Gallon 29.44565345676434 When you compile/run this program on NetBeans, if you have no compilation errors, you will go into execution. If so, your inputs will be requested down the bottom of the window. Enter the requested value and press Enter. There are a lot of assumptions in using the Scanner objects. We will get back to it later. But for now, it is expeditious to use.

  30. We will stop here • And return if we have time later…

  31. Summary • Chapter 2.2 focused on: • expressions and operator precedence • brief introduction to objects (out of place – chap 3) • accepting input from the user – using Buffered Reader • Data conversions

More Related