Ch. 4.pdf
Document Details
Uploaded by Deleted User
Full Transcript
Ch. 4 Fundamental Data Types Number Types Every value in Java is either: a reference to an object one of the primitive types Java has eight primitive types: four integer types two floating-point types two others Type...
Ch. 4 Fundamental Data Types Number Types Every value in Java is either: a reference to an object one of the primitive types Java has eight primitive types: four integer types two floating-point types two others Type Description Size 1 byte The type describing a single byte, with range -128... 127 byte short Primitive The short integerTypes type, with range -32768... 32767 2 bytes The integer type, with range -2,147,483,648 (Integer.MIN_VALUE).. 4 int. 2,147,483,647 (Integer.MAX_VALUE) bytes The long integer type, with range -9,223,372,036,854,775,808.. 8 long.9,223,372,036,854,775,807 bytes The double-precision floating-point type, with a range of about 8 double ±10308 and about 15 significant decimal digits bytes The single-precision floating-point type, with a range of about ±1038 4 float and about 7 significant decimal digits bytes The character type, representing code units in the Unicode encoding 2 char scheme bytes boolean The type with the two truth values false and true 1 bit Overflow Generally, you use int for integers Overflow occurs when: The result of a computation exceeds the range for the number type Overflow Example: 1012 is larger that the largest int The result is truncated to fit in an int No warning is given! Solution: use long instead Generally do not have overflow with the double data type Rounding Errors Rounding errors occur when an exact representation of a floating- point number is not possible. Floating-point numbers have limited precision. Not every value can be represented precisely, and roundoff errors can occur. Rounding Errors Example: Use double type in most cases Constants: static final ◦ If constant values are needed in several methods, ◦ Declare them with the instance variables of a class ◦ Tag them as static and final ◦ The static reserved word means that the constant belongs to the class, not the objects ◦ Format: Constants: static final Give static final constants public access to enable other classes to use them: Declaration of constants in the Math class Constants: static final Using a static constant: Public Static Constant Example Syntax 4.1 Constant Declaration Self Check 4.4 What is the difference between the following two statements? and Answer: The first declaration is used inside a method. The second declaration is used inside a class. Four Basic Arithmetic Operators Operation Symbol addition + subtraction - multiplication * division / Arithmetic Operators Expression: combination of variables, literals, operators, and/or method calls Parentheses control the order of the computation Multiplication and division have a higher precedence than addition and subtraction Mixing integers and floating-point values in an arithmetic expression yields a floating-point value Output: Integer Division Expression Result 7.0 / 4.0 1.75 7.0 / 4 1.75 7 / 4.0 1.75 7/4 1 Modulus Operator Expression Result 7%4 3 12 % 2 0 6 % 23 6 Integer Division and Remainder To determine the value in dollars and cents of 1729 pennies Obtain the dollars through an integer division by 100 To obtain the remainder, use the % operator Integer division and the modulus operator yield the dollar and cent values of a piggybank full of pennies. Increment and Decrement The ++ operator adds 1 to a variable (increments) The -- operator subtracts 1 from the variable (decrements) Figure 1 Incrementing a Variable: count++ Integer Division and Remainder Powers and Roots Math class contains methods sqrt and pow to compute square roots and powers To take the square root of a number, use Powers and Roots To compute xn, you write To compute x2 , it is significantly more efficient simply to compute: Powers and Roots In Java, can be represented as: Analyzing an Expression Mathematical Methods Converting Floats to Ints - Rounding Math.round() converts a floating-point number to nearest integer: If balance is 13.75, then rounded is set to 14. Arithmetic Expressions Calling Static Methods Cannot call a method on a number type Use a static method instead. Calling Static Methods A static method DOES NOT operate on an object: Static methods are declared inside classes Calling a static method: Converting Floats to Ints - Casting The compiler disallows the assignment of a double to an int because it is potentially dangerous: The fractional part is lost The magnitude may be too large Converting Floats to Ints - Casting You use a cast (typeName) to convert a value to a different type. Use the cast operator (int) to convert a convert floating-point value to an integer. Cast discards fractional part Reading Input System.in has minimal set of features Must be combined with other classes to be useful Use a class called Scanner to read keyboard input. Reading Input – Scanner class Import Scanner class: Create Scanner object: Use a Scanner method: Formatted Output Use the printf method to specify how values should be formatted. printf lets you print this: Instead of this: This command displays the price with two digits after the decimal point: Formatted Output You can also specify a field width: This prints 10 characters Six spaces followed by the four characters 1.22 Note: all values justify to the RIGHT by default. To justify to the left a negative sign is added before the field width: %-10.2f Formatted Output This command: Prints Formatted Output Formatted Output You can print multiple values with a single call to the printf method. Example: Output explained: Exercise Ask the user to enter 3 colors. Display all colors in a table. Match format of sample execution. Use printf Sample Executions: Exercise Solution String Type A string is a sequence of characters. String variable String literal String Method – length() Output: String Type A string of length 0 is called the empty string Contains no characters Is written as "" Concatenation Concatenation - Spaces Concatenation – Numbers and Strings Concatenation – less print statements Versus: String Method – toUpperCase() Output: 59 String Method – replace() replace method replaces ALL instances of a substring in a string with a new substring. Format: 60 String Method – replace() Output: 61 Method Arguments and Return Values 62 Practice Exercise ◦ Create a program that accepts a word from the user and converts that word into a password where all the vowels have been replaced with numbers. Then, display the user’s password. Uppercase Lowercase Vowels Vowels A – 0 a – 5 E – 1 e – 6 I – 2 i – 7 O – 3 o – 8 U – 4 u – 9 63 Practice Exercise Solution 64 String Input – next() method Escape Sequences - \" and \\ Indicates that the quotation mark that follows should be a part of the string and not mark the end of the string To include a backslash in a string, use the escape sequence \\ Escape Sequences - \n Strings and Characters A string is a sequences of Unicode characters. A character is a value of the type char. Characters have numeric values Character literals are delimited by single quotation marks. 'H' is a character. It is a value of type char Don't confuse them with strings "H" is a string containing a single character. It is a value of type String. Strings and Characters String positions are counted starting with 0. Strings and Characters – charAt() method Output: Substrings – substring() method Example: Substrings – substring() method To extract "World" Substrings – substring() method Result Sets tail to the string Substrings To make a string of one character, taken from the start of first Self Check 4.23 Consider this string variable Give a call to the substring method that returns the substring "gram". Answer: or Self Check 4.26 Give an input statement to read a name of the form “John Q. Public”. Assume the prompt has already been written. Answer: END