Presentation is loading. Please wait.

Presentation is loading. Please wait.

Char data type and the String class.

Similar presentations


Presentation on theme: "Char data type and the String class."— Presentation transcript:

1 char data type and the String class

2 Objectives: Learn about the char data type.
Learn about string literals Learn about String constructors and commonly used methods Understand immutability of strings Learn how to read string from the keyboard using the Scanner class The char data type is not in the AP Java subset, while strings are. However, any reasonable course will teach chars. One of the reasons for excluding char from the subset was the perceived danger of confusing a char constant 'x' with a string constant "x". An unstated objective of this chapter is to get a clear understanding that char and String are two different data types. char is a primitive data type; strings are objects.

3 ASCII Code

4 ASCII Code ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as 'a' or or an action of some sort. Indent between each set of matching curly brackets.

5 ASCII CHARACTER (CODE) NULL 16 1 17 2 18 3 19 4 20 5 21 6 22 7 [] 23 8 [Backspace] 24 9 [Horizontal Tab] 25 10 [Linefeed] 26 11 27 ← [Escape] 12 28 13  [Carriage Return] 29 14 30 15 31 Indent between each set of matching curly brackets.

6 32 <SPACE> 64 @ 96 ` 33 ! 65 A 97 a 34 " 66 B 98 b 35 # 67 C 99
ASCII CHARACTER 32 <SPACE> 64 @ 96 ` 33 ! 65 A 97 a 34 " 66 B 98 b 35 # 67 C 99 c 36 $ 68 D 100 d 37 % 69 E 101 e 38 & 70 F 102 f 39 ' 71 G 103 g 40 ( 72 H 104 h 41 ) 73 I 105 i 42 * 74 J 106 j 43 + 75 K 107 k 44 , 76 L 108 l Indent between each set of matching curly brackets.

7 45  - 77 M 109 m 46 . 78 N 110 n 47 / 79 O 111 o 48 80 P 112 p 49 1 81 Q 113 q 50 2 82 R 114 r 51 3 83 S 115 s 52 4 84 T 116 t 53 5 85 U 117 u 54 6 86 V 118 v 55 7 87 W 119 w 56 8 88 X 120 x 57 9 89 Y 121 y 58 : 90 Z 122 z 59 ; 91 [ 123 { 60 < 92 \ 124 | 61 = 93 ] 125 } 62 > 94 ^ 126 ~ 63 ? 95 _ 127 <> Indent between each set of matching curly brackets.

8 The char Data Type

9 char Data Type A char is a variable that holds a single character. Characters are represented by their ASCII values. char c = ‘A’; or char c = 65; means: 1. c is a char data type. 2. c is storing the value 65 which is the ASCII value for the character A. 65 c

10 char Is A Numeric Data Type
char c1 = ‘A’; System.out.println(c1); A

11 char Is A Numeric Data Type
char c1 = ‘A’; System.out.println(c1); System.out.println((int) c1); A 65

12 char Is A Numeric Data Type
char c1 = ‘A’; System.out.println(c1); System.out.println((int) c1); int i = 65; System.out.println(i); A 65 65

13 char Is A Numeric Data Type
char c1 = ‘A’; System.out.println(c1); System.out.println((int) c1); int i = 65; System.out.println(i); System.out.println((char) i); A 65 65 A

14 Adding Two chars Yields An int
char c1 = ‘A’; char c2 = ‘B’; System.out.println(c1 + c2); 131

15 Adding Two chars Yields An int
char c3 = c1 + c2; System.out.println(c3); possible loss of precision

16 Adding Two chars Yields An int
char c3 = (char) (c1 + c2); System.out.println(c3); ?

17 The String Class

18 The String class An object of the String class represents a string of characters. The String class belongs to the java.lang package, which is built into Java. Like other classes, String has constructors and methods. Unlike other classes, String has two operators, + and += (used for concatenation). There is no need to import java.lang.String because the java.lang package is imported automatically into all classes. The + and += operators for strings are an exception in Java, the only example of overloaded operators for objects.

19 The String class (cont’d)
There are two ways to declare an object of the String class: String jim = new String(“Jim Bowie”); System.out.println(jim); Jim Bowie

20 The String class (cont’d)
There are two ways to declare an object of the String class: String jim = new String(“Jim Bowie”); System.out.println(jim); String richard = “Richard Widmark”; Jim Bowie System.out.println(richard); Richard Widmark

21 The String class (cont’d)
Failing to assign a value to a String results in a null string. String nada; System.out.println(nada); Error - variable nada might not have been initialized

22 The String class (cont’d)
A null String is not the same as an empty String. String nada = “”; System.out.println(nada);

23 The String class (cont’d)
The length method: String state = “Texas”; int len = state.length(); System.out.println(len); 5

24 The String class (cont’d)
The length method: String state = “Texas”; System.out.println(state.length()); 5

25 The String class (cont’d)
The charAt method: char ch = state.charAt(2); System.out.println(ch); x

26 The String class (cont’d)
Character positions in strings are numbered starting from 0 String str = “Hello World”; Character positions in strings are counted starting from 0, so str.charAt(0) returns the first character and str.charAt(str.length() - 1) returns the last character. This is consistent with indices in arrays (Chapter 10): the index of the first element is 0.

27 The String class (cont’d)
The + operator is used to concatenate two or more string together. String city = “San Antonio”; String location = city + “, “ + state; System.out.println(location); San Antonio, Texas

28 The String class (cont’d)
Primitive data type can also be concatenated into a string using the + operator. int zipCode = 77040; location = location + zipCode; System.out.println(location); San Antonio, Texas 77040

29 The String class (cont’d)
String s1 = “hello”; System.out.println(s1); 3hello

30 The String class (cont’d)
String s2 = “hello” ; System.out.println(s2); hello12

31 The String class (cont’d)
String s3 = 5 – 3 + “hello”; System.out.println(s3); 2hello

32 The String class (cont’d)
String s4 = “hello” ; Error System.out.println(s4);

33 The String class (cont’d)
String s4 = “hello” + (5 – 2); System.out.println(s4); hello3

34 Immutability Once created, a string cannot be changed: none of its methods changes the string. Such types of objects are called immutable. Immutable objects are convenient because two references can point to the same object safely. There is no danger of changing an object through one reference without the others being aware of the change. If all the instance fields in a class are private and none of the methods can directly or indirectly set the field values, then the class’s objects are immutable. A few String methods create and return a different string, but none of them changes the string for which they were called. The Integer, Character, and Double classes, discussed later, are immutable, too.

35 String Literals

36 String Literals String literals are anonymous constant objects of the String class that are defined as text in double quotes. The string text may include “escape” characters. For example: "Biology” "C:\\jdk1.4\\docs” "Hello\n" \" stands for the double quote character. Like the char type, String objects internally represent characters using Unicode.

37 String Literals (cont’d)
don’t have to be constructed: they are “just there.” System.out.println(“Hello World”);

38 String Literals (cont’d)
can be assigned to String variables. String name = “Jim Bowie”; System.out.println(name);

39 String Literals (cont’d)
have methods you can call: System.out.println(“JVHS”.length()); System.out.println(“JVHS”.charAt(3));

40 The Scanner Class

41 Scanner (cont’d) Read the next word:
Scanner reader = new Scanner(System.in); String word = reader.next(); next() reads a single word and stores the string that is read into the variable word. The end of an word is indicated by any white space. This could be the Space Bar, the Tab Key, or the Enter key. When next() reads a word, it leaves the white space in the input buffer. If the word begins with white space, the white space is ignored and does not become part of the word.

42 Scanner (cont’d) Read the next line:
Scanner reader = new Scanner(System.in); String line = reader.nextLine(); nextLine() reads in an entire line and stores the string that is read into the variable line. The end of an input line is indicated by the escape sequence “\r\n”. These are the characters input when the Enter key is pressed When nextLine() reads a line of text, it reads the “\r\n” character, so the next reading of input begins on the next line The “\r\n” does not become part of the string value returned.

43 Scanner (cont’d) A string can have any number of characters, including zero characters "" is an empty string When a program executes the nextLine() method to read a line of text, and the user types nothing on the line but presses the Enter key, then the nextLine() method reads an empty string

44 Scanner (cont’d) The method nextLine() of the class Scanner reads the remainder of a line of text starting wherever the last keyboard reading left off This can cause problems when combining it with different methods for reading from the keyboard such as nextInt() Given the code, Scanner reader = new Scanner(System.in); int n = reader.nextInt(); String s1 = reader.nextLine(); String s2 = reader.nextLine(); and the input, 2 Heads are better than 1 head. what are the values of n, s1, and s2 after the code executes?

45 Scanner (cont’d) 2 Heads are better than 1 head. n = 2
int n = reader.nextInt(); 2 Heads are better than 1 head.

46 Scanner (cont’d) Heads are better than 1 head.
int n = reader.nextInt(); String s1 = reader.nextLine(); s1 = “” Heads are better than 1 head.

47 s2 = “Heads are better than”
Scanner (cont’d) int n = reader.nextInt(); String s1 = reader.nextLine(); String s2 = reader.nextLine(); s2 = “Heads are better than” Heads are better than 1 head.

48 s2 = “Heads are better than”
Scanner (cont’d) int n = reader.nextInt(); String s1 = reader.nextLine(); String s2 = reader.nextLine(); n = 2 s1 = “” s2 = “Heads are better than” 1 head.

49 Scanner (cont’d) 1 head. int n = reader.nextInt();
String s1 = reader.nextLine(); String s2 = reader.nextLine(); The last line was never read. 1 head.

50 Scanner (cont’d) 1 head. int n = reader.nextInt();
String s1 = reader.nextLine(); String s2 = reader.nextLine(); How Do We Fix The Problem? 1 head.

51 Scanner (cont’d) 2 Heads are better than 1 head.
int n = reader.nextInt(); 2 Heads are better than 1 head.

52 Scanner (cont’d) Heads are better than 1 head. n = 2
int n = reader.nextInt(); Heads are better than 1 head.

53 Scanner (cont’d) Heads are better than 1 head.
int n = reader.nextInt( ); reader.nextLine( ); Heads are better than 1 head.

54 Scanner (cont’d) Heads are better than 1 head.
int n = reader.nextInt( ); reader.nextLine( ); Heads are better than 1 head.

55 Scanner (cont’d) Heads are better than 1 head.
int n = reader.nextInt( ); reader.nextLine( ); String s1 = reader.nextLine( ); Heads are better than 1 head.

56 Scanner (cont’d) 1 head. int n = reader.nextInt( );
reader.nextLine( ); String s1 = reader.nextLine( ); s1 = “Heads are better than” 1 head.

57 Scanner (cont’d) 1 head. int n = reader.nextInt( );
reader.nextLine( ); String s1 = reader.nextLine( ); String s2 = reader.nextLine( ); 1 head.

58 Scanner (cont’d) int n = reader.nextInt( ); reader.nextLine( );
String s1 = reader.nextLine( ); String s2 = reader.nextLine( ); s2 = “1 head”

59 Scanner (cont’d) int n = reader.nextInt( ); reader.nextLine( );
String s1 = reader.nextLine( ); String s2 = reader.nextLine( ); n = 2 s1 = “Heads are better than” s2 = “1 head”

60 Top Down Design

61 Top-Down Programming WAP that reads the name, country of origin, width of the base, and the height of a pyramid. Calculate the surface area and the volume of the pyramid and display the results. There are many kinds of pyramids. The pyramids found in Egypt and South America are square pyramids. NOTE: The Surface Area has two parts: the area of the sides (the Lateral Area) and the area of the base (the Base Area). For this exercise we are going to solve only for the Lateral Area.

62 Java Programming Start JCreator.
Create a new file called “Lab03.java”. Save the new file in your Lab03 folder.

63 Top-Down Programming (cont’d)
The first step in programming is UNDERSTAND THE PROBLEM

64 Top-Down Programming (cont’d)
A pyramid is made by connecting a base to an apex.

65 Top-Down Programming (cont’d)
Volume = 1/3 × [Base Area] × Height Surface Area = 1/2 × Perimeter × [Side Length]

66 Top-Down Programming (cont’d)
Side Length =

67 Top-Down Programming (cont’d)
The second step programming is PLAN A SOLUTION

68 Top-Down Programming (cont’d)
What fields are required to solve the problem? NOTE: Fields should be the values we are solving for and the values we will read from the keyboard. double volume; double surfaceArea; String name; String country; double baseWidth; double height; Values to be calculate Values to be read from the keyboard

69 Top-Down Programming (cont’d)
The big picture is read the name of the pyramid, the country of origin, the base width, and the height of the pyramid from the keyboard, calculate the volume and surface area of the pyramid, and display the results on the console screen. How many methods do we need? 3

70 Top-Down Programming (cont’d)
Output will be fairly simple. We need a statement that displays the name of the pyramid, the surface area and the volume of the pyramid. <name> in <country> has a surface area of <Surface Area> square feet and a volume of <Volume> cubic feet.

71 Top-Down Programming (cont’d)
Input will also be very simple. We need prompts to precede each value entered. We need to read a line of text and then two doubles. Enter the Name of the pyramid: The Great Pyramid Of Giza Enter the Country of Origin: Egypt Enter the base width: Enter the height:

72 Top-Down Programming (cont’d)
Process is a more complex method and will involve several calculations. We need to calculate the volume. We need to calculate the surface area. The formula for surface area requires the side length (which is the hypotenuse of a right triangle).

73 Top-Down Programming (cont’d)
volume = 1/3 * base area * height side length = sqrt( (baseWidth/2)2 + height2 ) surface area = 2 * base width * side length

74 Top-Down Programming (cont’d)
The third step programming is WRITE THE PROGRAM

75 Top-Down Programming (cont’d)
Start JCreator. Create a new file called “Lab03.java”. Save the new file in your Lab03 folder.

76 Top-Down Programming (cont’d)
import java.util.Scanner; We will be using the Scanner class so we need an import statement.

77 Top-Down Programming (cont’d)
import java.util.Scanner; public class Lab05 { }

78 Top-Down Programming (cont’d)
In the planning phase we determined that we need six instance fields to solve the problem.

79 Top-Down Programming (cont’d)
public class Lab05 { private double volume; private double surfaceArea; private String name; private String country; private double baseWidth; private double height; }

80 Top-Down Programming (cont’d)
The “big problem” is defined in the main method.

81 Top-Down Programming (cont’d)
public static void main(String[] args) { }

82 Top-Down Programming (cont’d)
public static void main(String[] args) { Lab03 lab = new Lab03( ); }

83 Top-Down Programming (cont’d)
public static void main(String[] args) { Lab03 lab = new Lab03( ); lab.input(); // Enter data from the kybd }

84 Top-Down Programming (cont’d)
public static void main(String[] args) { Lab03 lab = new Lab03( ); lab.input(); // Enter data from the kybd lab.process( ); // Calculate Vol and SA }

85 Top-Down Programming (cont’d)
public static void main(String[] args) { Lab03 lab = new Lab03( ); lab.input(); // Enter data from the kybd lab.process( ); // Calculate Vol and SA lab.output( ); // Display output }

86 Top-Down Programming (cont’d)
input(), process( ), and output( ) are the smaller parts of the problem. Write stubs for input(), process( ), and output( ).

87 Top-Down Programming (cont’d)
public void input() { } public void process() public void output() NOTE: Usually methods are given public access.

88 Top-Down Programming (cont’d)
The smaller parts can be solved in any order. Do you need to know how input works in order to write the process method? Do you need to know how process works in order to write the output method? Do you need to know how output works in order to write the input method?

89 Top-Down Programming (cont’d)
input( )

90 Top-Down Programming (cont’d)
Scanner reader = new Scanner(System.in); System.out.print("Enter the Name of the pyramid: "); name = reader.nextLine(); System.out.print("Enter the Country of Origin: "); country = reader.next(); System.out.print("Enter the base width: "); baseWidth = reader.nextDouble(); System.out.print("Enter the height: "); height = reader.nextDouble(); public void input() { }

91 Top-Down Programming (cont’d)
output( )

92 Top-Down Programming (cont’d)
public void output() { }

93 Top-Down Programming (cont’d)
public void output() { System.out.println(name + “ in “ + country + " has a surface area of " + surfaceArea + " square feet"); }

94 Top-Down Programming (cont’d)
public void output() { System.out.println(name + “ in “ + country + " has a surface area of " + surfaceArea + " square feet"); System.out.println("and a volume of " + volume + " cubic feet."); }

95 Top-Down Programming (cont’d)
process( )

96 Top-Down Programming (cont’d)
public void process() { }

97 Top-Down Programming (cont’d)
public void process() { volume = 1/3.0 * baseWidth * baseWidth * height; }

98 Top-Down Programming (cont’d)
public void process() { volume = 1/3.0 * baseWidth * baseWidth * height; double sideLength = Math.hypot(baseWidth/2, height); }

99 Top-Down Programming (cont’d)
public void process() { volume = 1/3.0 * baseWidth * baseWidth * height; double sideLength = Math.hypot(baseWidth/2, height); surfaceArea = 2 * baseWidth * sideLength; }

100 Top-Down Programming (cont’d)
Run The Program: (1st Run) Enter the Name of the pyramid: The Great Pyramid of Khufu Enter the Country of Orgin: Egypt Enter the base width: 755.9 Enter the height: 480.6 The Great Pyramid of Khufu in Egypt has a surface area of 924,330.1 square feet and a volume of 91,535, cubic feet.

101 Top-Down Programming (cont’d)
Run The Program: (2nd Run) Enter the Name of the pyramid: The Pyramid of Menkaure Enter the Country of Orgin: Egypt Enter the base width: 355.9 Enter the height: 218 The Pyramid of Menkaure in Egypt has a surface area of 200, square feet and a volume of 9,204, cubic feet.

102 Java Begin Lab 03 Object Oriented Programming
The material in this chapter is not tested on the AP CS exams.


Download ppt "Char data type and the String class."

Similar presentations


Ads by Google