Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 PRIMITIVE DATA TYPES Computer programs operate on data values. Values in Java are classified according to their.

Similar presentations


Presentation on theme: "1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 PRIMITIVE DATA TYPES Computer programs operate on data values. Values in Java are classified according to their."— Presentation transcript:

1 1 Chapter 2 JAVA FUNDAMENTALS CONT’D

2 2 PRIMITIVE DATA TYPES Computer programs operate on data values. Values in Java are classified according to their data type. The data type of a value determines how the value is represented in the computer and the kinds of operations that can be performed on the value.

3 3 PRIMITIVE DATA TYPES Numeric Data Types Numeric values can be divided into two classifications: Integer Floating-point Integers are whole numbers: 294111123–950 Floating-point numbers are real values - values that may have a decimal point: 12.4169.5–1347.98

4 4 PRIMITIVE DATA TYPES Numeric Data Types The integer and floating-point classifications are separated into a number of types that differ in the amount of storage allocated and the range of values that can be stored.

5 5 PRIMITIVE DATA TYPES Numeric Data Types Table 2-5 text

6 6 PRIMITIVE DATA TYPES Numeric Data Types Integer Date Types Integer data types are used for storing whole numbers. Example: byte rating; int offset; long acctNum; short days; offset = 7; acctNum = 1234567890;

7 7 PRIMITIVE DATA TYPES Numeric Data Types Integer Date Types - Integer Literals When you write an integer literal in a Java program, it is stored as a type int by default. Example: byte rating; int offset; long acctNum; short days; offset = 7; acctNum = 1234567890; The values 7 and 1234567890 are stored as literals of type int.

8 8 PRIMITIVE DATA TYPES Numeric Data Types Floating-Point Data Types Floating-point data types are used for holding numeric values that may include a decimal point - real numbers. The float data type is considered a single-precision data type. It can hold a floating-point number with 7 digits of accuracy. The double data type uses twice as much memory as the float data type; it is the double-precision floating-point data type. The double can hold a floating-point value with 15 digits of accuracy.

9 9 PRIMITIVE DATA TYPES Numeric Data Types Floating-Point Data Types The statements below declare two floating-point variables. The assignment statement gives the variable named range the value 5.5. double range; float amount; range = 5.5;

10 10 PRIMITIVE DATA TYPES Numeric Data Types Floating-Point Data Types Floating-point values are typically stored inside the computer in a notation similar to scientific notation, called E notation. *** See Table 2-6 of the text

11 11 PRIMITIVE DATA TYPES Numeric Data Types Floating-Point Data Types - Floating-Point Literals Floating-point literals are stored in memory as type double. double range; float amount; range = 5.5; The literal, 5.5, used in this statement is stored as data type double.

12 12 PRIMITIVE DATA TYPES Numeric Data Types Floating-Point Data Types - Floating-Point Literals A problem can arise when you assign a floating-point literal to a variable of type float. Java is a strongly typed language, which means it will only let you store a value of a compatible data type in a variable.

13 13 PRIMITIVE DATA TYPES Numeric Data Types Floating-Point Data Types - Floating-Point Literals Example: Since a double value can be much larger than a variable of type float can hold, the assignment statement below, which assigns the value 27.98 to the variable named amount, will produce a compiler error. double range; float amount; amount = 27.98; This is an error! You are trying to assign a value of type double to a variable of type float.

14 14 PRIMITIVE DATA TYPES Numeric Data Types Floating-Point Data Types - Floating-Point Literals You can get around this problem by specifying that the floating-point literal be stored as a type float by using the suffix F (can also be lowercase f) after the literal. Example: The following segment will work. double range; float amount; amount = 27.98F; We used a suffix F after the literal value to specify that the value be stored as a float. Now we are assigning a value of type float to a variable of type float.

15 15 PRIMITIVE DATA TYPES The boolean Data Type Expressions that evaluate to a true or false value are called Boolean expressions. The boolean data type allows you to create variables that can have either the value true or the value false. The word boolean is a key word. Example: boolean badInput; badInput = false; The contents of a boolean variable may not be copied to a variable of any other data type.

16 16 PRIMITIVE DATA TYPES The char Data Type A variable of type char, meaning character, can be used to store a single character. The word char is a key word. Example: char grade; grade = 'A';

17 17 PRIMITIVE DATA TYPES The char Data Type Character constants/literals are enclosed in single quotation marks as in 'A'. char grade; grade = 'A'; If you leave off the quotation marks, the compiler will interpret A is a variable. A character literal is enclosed in single quotation marks.

18 18 PRIMITIVE DATA TYPES The char Data Type 'A' is not equivalent to "A". "A" is a string literal. String literals cannot be assigned to character variables. Example: The assignment statement below is erroneous: char grade; grade = “A”; This is a syntax error! You cannot assign a string literal to a variable of type char.

19 19 PRIMITIVE DATA TYPES The char Data Type Characters are actually encoded in binary (sequences of ones and zeroes). Java uses Unicode to encode characters. Unicode uses 16 bits (2 bytes) to encode each character. *** See Appendix B of the text

20 20 PRIMITIVE DATA TYPES The char Data Type

21 21 VARIABLE ASSIGNMENT AND INITIALIZATION The assignment operator (=) takes two operands. The operand on the left of the assignment operator must correspond to a location in memory whose contents may be changed. The operand on the right of the assignment operator can be any expression that has a value. An assignment statement copies the value of the expression that is the right operand of the assignment operator into the memory location corresponding to the left operand of the assignment operator. The assignment operator does not change the contents of its right operand.

22 22 VARIABLE ASSIGNMENT AND INITIALIZATION Problem: What are the values of x, y, and z after the following segment of a program has executed? x = ____, y = ____, z = ____ double x, y, z; x = 1.1; y = 2.2; z = 3.3; z = x;

23 23 VARIABLE ASSIGNMENT AND INITIALIZATION You may give a variable an initial value when you declare the variable. This is called initializing the variable. Examples: char letterGrade = 'A'; float salary = 564248.56F, bonus, retirement = 175.00f; Notice that the variable bonus is uninitialized.

24 24 VARIABLE ASSIGNMENT AND INITIALIZATION In Java it is an error to use a variable that is defined inside a method before giving it a value. Therefore, be sure variables are given a value before using them in a calculation or displaying their contents.

25 25 THE String CLASS A string is a sequence of characters. Java does not have a primitive data type for holding strings. The Java API includes a class named String. Objects of the String class can be used to store and process strings.

26 26 THE String CLASS Objects and Classes Objects are software entities that have attributes and methods. –An object's attributes are data values that are stored in the object. –An object's methods are procedures that perform operations on the object's attributes.

27 27 THE String CLASS Objects and Classes Programmers design classes. The programmer determines the attributes and methods that are needed and then creates a class. A class is a pattern from which objects are created/instantiated.

28 28 THE String CLASS Variables of Primitive Data Types vs. Class Type Variables A variable of a primitive data type, like int, long, float, double, char, boolean, etc. holds an actual data value. Example: The statement below declares and initializes a variable of the primitive data type int. The variable named number contains the data value 25. int number = 25;

29 29 THE String CLASS Variables of Primitive Data Types vs. Class Type Variables As illustrated below the variable named number holds the actual data value, 25. int number = 25; number25

30 30 THE String CLASS Variables of Primitive Data Types vs. Class Type Variables A class type variable holds the memory address of an object. We say that a class variable references the object or is a reference variable. Example: The statement below declares a variable that can store the address of a String object, creates an object of the String class in memory that contains the string “1600 Pennsylvania Avenue”, and assigns the address of this object to the variable named street. String street = new String("1600 Pennsylvania Avenue");

31 31 THE String CLASS Variables of Primitive Data Types vs. Class Type Variables As illustrated below the variable named street holds the address of a String object. String street = new String("1600 Pennsylvania Avenue"); address A String object 1600 Pennsylvania Avenue street

32 32 THE String CLASS The first step in using an object of the String class is to declare a variable of the String type. This can be accomplished with a statement like the following: String street; This statement declares a variable named street that can reference (hold the address of) an object of the String class.

33 33 THE String CLASS We can create/instantiate an object of the String class using the new operator. List the type of object you wish to create after the new operator. The new operator returns the address of the object created. Example: The statement below creates an object of the String class that holds the string “1600 Pennsylvania Avenue” and assigns the address of this object to the reference variable named street. street = new String("1600 Pennsylvania Avenue");

34 34 THE String CLASS Java provides a shorthand way of creating a String object. Example: The following statement creates a String object in memory and stores the address of this object in the variable named street. street = "1600 Pennsylvania Avenue"; Notice we did not use the new operator to create the String object. Note: Objects of other classes cannot be created in a similar way.

35 35 THE String CLASS When you send the name of a variable that references a String object to the println method, the string contained in the object is displayed in a console window. Example: When the following segment is executed the message The street address is: 1600 Pennsylvania Avenue is displayed on a line on the computer screen. String street = "1600 Pennsylvania Avenue"; System.out.print("The street address is: "); System.out.println(street);

36 36 THE String CLASS The following segment produces the same output as the previous segment: String street = "1600 Pennsylvania Avenue"; System.out.println("The street address is: " + street);

37 37 THE String CLASS Objects of the String class have numerous methods for working with strings. *** See Table 2-15 of the text for some of these

38 38 THE String CLASS The length Method Objects of the String class have a method named length, which returns the number of characters in the string, including spaces. Example: The value 24 would be assigned to the integer variable named numChars in the segment below: int numChars; String street = "1600 Pennsylvania Avenue"; numChars = street.length( );

39 39 THE String CLASS The length Method We are calling the length method of the object referenced by street by writing street.length( ). When we call a method, we are saying execute the method. Notice that the parentheses following the method name length are empty. The length method does not expect any input data values, arguments, hence we are not passing any. int numChars; String street = "1600 Pennsylvania Avenue"; numChars = street.length( );

40 40 THE String CLASS The length Method The length method returns the int value that is the number of characters in the string. This means the length method sends an int back to the statement that called it. The call to the method has the value 24 in the segment below. We are assigning this value to numChars. int numChars; String street = "1600 Pennsylvania Avenue"; numChars= street.length( ); Remember, the quotation marks delimit a string in the source code, but they are not stored in the String object. The length of this string is 24.

41 41 THE String CLASS The charAt Method Objects of the String class have a method named charAt, which returns the character at the specified index in the string. The first character in a string is at index 0; the second character is at index 1, etc. Example: The character '6' would be assigned to the character variable named letter in the segment below: char letter; String street = "1600 Pennsylvania Avenue"; letter = street.charAt(1); Notice, charAt returns a value of data type char.

42 42 THE String CLASS The charAt Method Problem: What will be displayed when the println statement below is executed? String street = "1600 Pennsylvania Avenue"; System.out.println("The character is: " + street.charAt(18)); Answer:

43 43 THE String CLASS The toLowerCase Method Objects of the String class have a method named toLowerCase, which creates an object containing the lowercase equivalent of the string contained in the calling object and returns the address of the newly created String object.

44 44 THE String CLASS The toLowerCase Method Example: The variable named newString will reference an object containing the string “1600 pennsylvania avenue” after the statements below are executed. The string in the object referenced by street is unchanged after the statements are executed; It still contains the string “1600 Pennsylvania Avenue”. String newString; String street = "1600 Pennsylvania Avenue"; newString = street.toLowerCase( );

45 45 THE String CLASS The toUpperCase Method Objects of the String class have a method named toUpperCase, which creates an object containing the uppercase equivalent of the string contained in the calling object and returns the address of the newly created String object.

46 46 THE String CLASS The toUpperCase Method Example: The variable named anotherString will reference an object containing the string "1600 PENNSYLVANIA AVENUE" after the statements below are executed. The string in the object referenced by street is unchanged after the statements are executed; It still contains the string “1600 Pennsylvania Avenue”. String anotherString; String street = "1600 Pennsylvania Avenue"; anotherString = street.toUpperCase( );

47 47 THE String CLASS The String methods discussed in the preceding slides do not change the original String object. The toLowerCase and toUpperCase methods create new String objects. *** See the Java API for additional methods of the String class.

48 48 READING INPUT FROM THE KEYBOARD Previously, we learned that the standard output device is a console window and the System.out object is associated with the standard output device. The standard input device is normally the computer keyboard. The Java API has an object System.in which is associated with the standard input device.

49 49 READING INPUT FROM THE KEYBOARD The Scanner Class We will use the System.in object in conjunction with the Scanner class to read input data from the keyboard. The Scanner class has methods that can be used to read input and format it as either a value of a primitive data type or a String.

50 50 READING INPUT FROM THE KEYBOARD The Scanner Class To use the Scanner class in our program we must put the following statement near the top of our file, before any class definition: import java.util.Scanner; This statement tells the compiler where to find the Scanner class in the Java API.

51 51 READING INPUT FROM THE KEYBOARD The Scanner Class You must also create a Scanner object and connect it to the System.in object. You can do this with a statement like the following: Scanner keyboard = new Scanner(System.in); Create this object inside your main method before you attempt to read anything from the keyboard.

52 52 READING INPUT FROM THE KEYBOARD The Scanner Class The words Scanner keyboard declare a variable named keyboard of type Scanner. This variable will reference an object of the Scanner class. Scanner keyboard = new Scanner(System.in); You could have chosen any name you wanted for the variable, but keyboard is a good one since you are going to use it to access the keyboard.

53 53 READING INPUT FROM THE KEYBOARD The Scanner Class Scanner keyboard = new Scanner(System.in); The new key word is used to create an object in memory. In the statement above we are creating an object of the Scanner class. Inside the parentheses, we have System.in. Here we are saying that we want the object we are creating to be connected with the System.in object, which again is associated with the keyboard. We are assigning the address of the object created using the new operator to our variable named keyboard, so keyboard now references the object we have linked with the actual keyboard.

54 54 READING INPUT FROM THE KEYBOARD The Scanner Class Every object created from the Scanner class has methods that read a string of characters entered at the keyboard, convert them to a specified type, and return the converted value. This value can be stored in a variable of compatible type.

55 55 READING INPUT FROM THE KEYBOARD The Scanner Class For example, the code below could be used to read an integer entered at the keyboard and store it in an integer variable named age. int age; System.out.print(“Enter your age: “); age = keyboard.nextInt( );

56 56 READING INPUT FROM THE KEYBOARD The Scanner Class The statement highlighted below is called a prompt: int age; System.out.print(“Enter your age: “); age = keyboard.nextInt( ); A prompt is a message that lets the user know what input is expected. Whenever you want the user to enter a value at the keyboard, you must display an appropriate prompt on the computer screen.

57 57 READING INPUT FROM THE KEYBOARD The Scanner Class Below we are calling the nextInt( ) method of the object referenced by keyboard to get a value entered by the user at the keyboard. int age; System.out.print(“Enter your age: “); age = keyboard.nextInt( ); The nextInt( ) method formats the characters entered by the user as an int and returns the integer value. The integer value is assigned to the variable named age.

58 58 READING INPUT FROM THE KEYBOARD The Scanner Class If you had named your Scanner variable something else, say dog, the previous segment would need to be changed as follows: Scanner dog = new Scanner(System.in); int age; System.out.print("Enter your age: "); age = dog.nextInt( ); Every object of the Scanner class has the member methods listed in Table 2-17 of the text.

59 59

60 60 READING INPUT FROM THE KEYBOARD The Scanner Class *** See Table 2-17 of the text for a listing of some useful methods of the Scanner class *** See the Java API online

61 61 READING INPUT FROM THE KEYBOARD The Scanner Class *** See the program RectangleArea.java on webct for an example of the usage of the Scanner class.

62 62 READING INPUT FROM THE KEYBOARD The Scanner Class We can use the nextLine method of a Scanner object to read a string of characters entered at the keyboard. Example: To get the user's first name we could write: String firstName; System.out.print("Enter your first name: "); firstName = keyboard.nextLine( );

63 63 READING INPUT FROM THE KEYBOARD The Scanner Class The nextLine method creates a String object in memory that contains the sequence of characters entered at the keyboard before the Enter key is pressed and returns the address of this object. Below we are assigning the address of the object created by the nextLine method to the String reference variable named firstName. String firstName; System.out.print("Enter your first name: "); firstName = keyboard.nextLine( ); The nextLine method creates a String object in memory and returns the address of the object created.

64 64 READING INPUT FROM THE KEYBOARD The Scanner Class Calling a Scanner object's nextLine method following a call to its' nextInt, nextDouble, or other methods for reading a value of a primitive data type can cause a problem. *** See the program InputProblem.java from the text

65 65 READING INPUT FROM THE KEYBOARD The Scanner Class When the user types keystrokes at the keyboard, the keystrokes are stored in area of memory called the keyboard buffer. When the user presses the Enter key, a newline character is written to the keyboard buffer. The Scanner classes methods that read values of primitive data types, skip leading newline characters and stop reading at a trailing newline character, leaving the trailing newline character in the keyboard buffer.

66 66 READING INPUT FROM THE KEYBOARD The Scanner Class The nextLine method does not skip leading newline characters. The nextLine method reads characters from the keyboard buffer until it reads its first newline character. The nextLine method does not put the newline in the String object, but does advance the read position past it. You might say the nextLine method consumes the newline character, but the other methods we have learned do not.

67 67 READING INPUT FROM THE KEYBOARD The Scanner Class When a call to the nextLine method reads a newline character that was left in the buffer by a preceding read using one of the other methods of the String class, it appears that the nextLine call was skipped, because it does not read any other characters. We can fix this problem by inserting another call to the nextLine method to read past the problematic newline character.

68 68 READING INPUT FROM THE KEYBOARD The Scanner Class *** See the program CorrectedInputProblem.java on webct

69 69 READING INPUT FROM THE KEYBOARD The Scanner Class The Scanner class does not have a method for reading a single character. In the text, they suggest using the Scanner classes nextLine method to read the character as a string, and then using the String classes charAt method to extract the first character from the string. Remember, the first character is at index 0.

70 70 READING A SINGLE CHARACTER ENTERED AT THE KEYBOARD Example: String stringInitial; char initial; System.out.print("Enter your middle initial " ); stringInitial = keyboard.nextLine( ); initial = stringInitial.charAt(0);

71 71 MORE ON THE String CLASS *** See the program StringDemo.java on webct


Download ppt "1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 PRIMITIVE DATA TYPES Computer programs operate on data values. Values in Java are classified according to their."

Similar presentations


Ads by Google