html5-img
1 / 59

Lecture 4 Assignment and Expressions

Lecture 4 Assignment and Expressions. Richard Gesick. Assigning Values to Variables. Assignment operator = Value on the right of the operator is assigned to the variable on the left

micheal
Download Presentation

Lecture 4 Assignment and Expressions

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. Lecture 4Assignment and Expressions Richard Gesick

  2. Assigning Values to Variables Assignment operator = • Value on the right of the operator is assigned to the variable on the left • Value on the right can be a literal (text representing a specific value), another variable, or an expression (a valid combination of variables, operators, and constants -- explained in detail later) Examples: x = 20; // x gets 20 y = x; // y gets the value of x (20)

  3. Assigning Initial Values to Variables Syntax for declaring variables and assigning initial values: dataTypevariableName = initialValue; or dataType variable1 = initialValue1, variable2 = initialValue2, …; Examples: int age = 19; // age, an int, gets 19 // taxRate, a double, gets .20 // salesTax, also a double, gets .06 double taxRate = .20, salesTax = .06;

  4. Literals • int, short, byte Optional initial sign (+ or -) followed by digits 0 – 9 in any combination. • long Optional initial sign (+ or -) followed by digits 0–9 in any combination, terminated with an L or l. *Use the capital L because the lowercase l can easily be confused with the number 1. • Integer literals that begin with 0 are considered to be octal values; Integer literals that begin with 0x are considered to be hexadecimal values.

  5. Floating-Point Literals • float Optional initial sign (+ or -) followed by a floating-point number in fixed or scientific format, terminated by an F or f. • double Optional initial sign (+ or -) followed by a floating-point number in fixed or scientific format.

  6. Common Error Trap Commas, dollar signs, and percent signs (%) cannot be used in integer or floating-point literals.

  7. char and boolean Literals • char • Any printable character enclosed in single quotes • A decimal value from 0 – 65535 • '\m' , where \m is an escape sequence. For example, '\n' represents a newline, and '\t' represents a tab character. • boolean true orfalse See Example 2.3 Variables.java

  8. Assigning the Values of Other Variables Syntax: dataType variable2 = variable1; • Rules: 1. variable1 needs to be defined before this statement appears in the source code 2.variable1 and variable2 need to be compatible data types; in other words, the precision of variable1 must be lower than or equal to that of variable2.

  9. Compatible Data Types Avariable of any type in right column can be assigned to a variable of any type in left column: Data TypeCompatible Data Types byte byte short byte, short int byte, short, int, char long byte, short, int, long, char float float, byte, short, int, long, char double float, double, byte, short, int, long, char boolean boolean char char

  10. Sample Assignments • This is a valid assignment: float salesTax = .05f; double taxRate = salesTax; • This is invalid because the float data type is lower in precision than the double data type: double taxRate = .05; float salesTax = taxRate;

  11. Common Error Trap Declare a variable only once After a variable is declared, its data type cannot be changed. These statements: double twoCents; double twoCents = .02; generate this compiler error: twoCents is already defined

  12. Common Error Trap After a variable is declared, its data type cannot be changed. These statements: double cashInHand; intcashInHand; generate this compiler error: cashInHand is already defined

  13. String Literals • String is a class, not a basic data type; String variables are objects • String literal: text contained within double quotes. Examples of String literals: "Hello" "Hello world" "The value of x is "

  14. String Concatenation Operator (+) • Combines String literals with other data types for printing Example: String word1 = "Hello"; String word2 = "there!"; String greeting = word1 + ' ' + word2; System.out.println( greeting ); output is: Hello there!

  15. Common Error Trap • String literals must start and end on the same line. This statement: System.out.println( "Never pass a water fountain without taking a drink" ); generates several compiler errors: • Break long Strings into shorter Strings and use the concatenation operator: System.out.println( "Never pass a water " + "fountain without taking a drink" );

  16. Escape Sequences To include a special character in a String, use an escape sequence Character Escape Sequence Newline \n Tab \t Double quotes \" Single quote \' Backslash \\ Backspace \b Carriage return \r Form feed \f

  17. Constants • Sometimes you know the value of a data item, and you know that its value will not (and should not) change during program execution. In this case, it is good to define that data item as a constant. Syntax: finaldataTypeconstantIdentifier =assignedValue; Note: assigning a value when the constant is declared is optional. But a value must be assigned before the constant is used and cannot be changed later in the program.

  18. SOFTWARE ENGINEERING TIP Declare as a constant any data that should not change during program execution Use all capital letters for constants and separate words with an underscore: Example: final double TAX_RATE = .05; Declare constants at the top of the program so their values can easily be seen

  19. Expressions and Arithmetic Operators • The Assignment Operator and Expressions • Arithmetic Operators • Operator Precedence • Integer Division and Modulus • Division by Zero • Mixed-Type Arithmetic and Type Casting • Shortcut Operators

  20. Assignment Operator Syntax: target = expression; expression: operators and operands that evaluate to a single value -- value is then assigned to target -- target must be a variable (or constant) -- value must be compatible with target's data type

  21. Examples: int numPlayers = 10; // numPlayers gets 10 numPlayers = 8; // numPlayers now gets 8 int legalAge = 18; // legalAge gets 18 int voterAge = legalAge; // voterAge gets 18 The next statement is illegal int length = width * 2; // width is not yet defined int width = 20; and generates the following compiler error: cannot find symbol

  22. Arithmetic Operators

  23. Operator Precedence • If more than one operator is used in an expression the order of evaluation is determined using operator precedence. • Expressions in parentheses are evaluated first • Multiplication, division, and modulus are performed before addition and subtraction • When multiple arithmetic operators of the same precedence occur in one expression, they are evaluated left to right. • Assignment is performed last, and is performed right to left.

  24. Operator Precedence

  25. Example You have 2 quarters, 3 dimes, and 2 nickels. How many pennies are these coins worth? int pennies = 2 * 25 + 3 * 10 + 2 * 5; = 50 + 30 + 10 = 90 Note: * has higher precedence than +, so the multiplications are executed first, left to right, then the additions, left to right.

  26. Another Example Translate x into Java: 2y // This is incorrect! double result = x / 2 * y; => x* y 2 // This is correct // Parentheses force evaluation of 2 * y double result = x / ( 2 * y );

  27. Integer Division and Modulus When two integers are divided • the quotient is an integer • any fractional part is truncated (discarded) • To get the remainder, use the modulus operator with the same operands

  28. Division by Zero • Integer division by 0: Example: int result = 4 / 0; At run time, the JVM generates an ArithmeticExceptionand the program stops executing. • Floating-point division by 0: • If the dividend is not 0, the result is Infinity • If the dividend and divisor are both 0, the result is NaN (not a number)

  29. Mixed-Type Arithmetic • When performing calculations with operands of different data types: • Lower-precision operands are promoted to higher-precision data types, then the operation is performed • Promotion is effective only for expression evaluation; not a permanent change • This is called implicit type casting. • Bottom line: any expression involving a floating-point operand will have a floating-point result.

  30. Rules of Promotion The compiler applies the first of these rules that fits: • If either operand is a double, the other operand is converted to a double. • If either operand is a float, the other operand is converted to a float. • If either operand is along, the other operand is converted to a long. • If either operand is an int, the other operand is promoted to an int • If neither operand is a double, float, long, or an int, both operands are promoted to int.

  31. Explicit Type Casting Syntax: (dataType)( expression ) Note: parentheses around the expression are optional if the expression consists of only one variable Example: calculating a floating-point average of integers double average = (double)(total) / count;

  32. Shortcut Operators ++ increment by 1 -- decrement by 1 Example: count++; // count = count + 1; count--; // count = count - 1; Postfix version (var++, var--): use value of varin expression, then increment or decrement. Prefix version (++var, --var): increment or decrement var, then use value in expression

  33. Shortcut Arithmetic Operators

  34. Common Error Trap No spaces are allowed between the arithmetic operator and the equals sign Note that the correct sequence is +=, not =+ Example:add 2 to a // this is incorrect a =+ 2; // assigns +2 to a // this is correct a += 2; // a = a + 2;

  35. Operator Precedence

  36. The String Class Represents a sequence of characters Examples: String greeting = new String( "Hello" ); String empty = new String( );

  37. String Concatenation Operators + appends a String to another String. At least one operand must be a String. += String concatenation operator Example: String s1 = new String( "Hello " ); String s2 = "there. "; String s3 = s1 + s2; // s3 is: // Hello there String s3 += "!"; // s3 is now: // Hello there!

  38. Example String greeting = "Hello"; intlen = greeting.length( ); The value of len is 5 The length Method

  39. Example: String greeting = "Hello"; greeting = greeting.toUpperCase( ); The value of greeting is "HELLO" toUpperCaseandtoLowerCase Methods

  40. The index of the first character of a String is 0. Example: String greeting = "Hello"; int index = greeting.indexOf( 'e' ); The value of index is 1. The indexOf Methods

  41. Example String greeting = "Hello"; char firstChar = greeting.charAt( 0 ); The value of firstChar is 'H' The charAt Method

  42. Example: String greeting = "Hello"; String endOfHello = greeting.substring( 3, hello.length( ) ); The value of endOfHello is “lo” The substring Method

  43. Common Error Trap Specifying a negative start index or a start index past the last character of the String will generate a StringIndexOutOfBoundsException. Specifying a negative end index or an end index greater than the length of the String also will generate aStringIndexOutOfBoundsException

  44. Formatting Numeric Output The DecimalFormat class and the NumberFormat class allow you to specify the number of digits for printing and to add dollar signs and percent signs to your output, • Both classes are in the java.text package. • We will cover the NumberFormat class later.

  45. The DecimalFormat Class Pattern characters: 0 required digit, include if 0 # optional digit, suppress if 0 . decimal point , comma separator % multiply by 100 and display a percent sign

  46. The DecimalFormatformat Method To format a numeric value for output, call the format method.

  47. The Random Class Generates a pseudorandom number (appearing to be random, but mathematically calculated) The Random class is in the java.utilpackage. Example: Random random = new Random( );

  48. The nextInt Method Example: to generate a random integer between 1 and 6: int die = random.nextInt( 6 ) + 1;

  49. Input Using the Scanner Class • Provides methods for reading byte, short, int, long, float, double, and String data types from the Java console and other sources • Scanner is in the java.util package • Scanner parses (separates) input into sequences of characters called tokens. • By default, tokens are separated by standard white space characters (tab, space, newline, etc.)

  50. A Scanner Constructor Example: Scanner scan = new Scanner( System.in );

More Related