1 / 31

Chapter 6

Chapter 6 Strings Arrays Outline 6.1 Language Support 6.1.1 The String Class 6.1.2 The Masquerade and the + Operator 6.2 String Handling 6.2.1 Overview of String Methods 6.2.2 Accessors 6.2.3 Transformers 6.2.4 Comparators 6.2.5 Numeric Strings

Ava
Download Presentation

Chapter 6

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 6 Strings Arrays

  2. Outline 6.1 Language Support 6.1.1 The String Class 6.1.2 The Masquerade and the + Operator 6.2 String Handling 6.2.1 Overview of String Methods 6.2.2 Accessors 6.2.3 Transformers 6.2.4 Comparators 6.2.5 Numeric Strings 6.3 Applications 6.3.1 Character Frequency 6.3.2 Character Substitution 6.3.3 Fixed-Size Codes 6.3.4 Variable-Size Codes 6.4 Advanced String Handling 6.4.1 The StringBuffer Class

  3. Outline ArraysIntroduction 1-D Arrays 2-D Arrays

  4. 6.1 Language Support Write a fragment that creates a String that encapsulates “York”

  5. Are Strings Special? Write a fragment that creates a String that encapsulates “York” String s = new String("York"); Creating strings is not different from creating any other object.

  6. The Masquerade Can create a String without using new: String s = "York"; The compiler replaces the above with: String s = new String("York");

  7. The + Operator Can concatenate two strings using a "fake" operator: String s = "York" + "Lane"; The compiler replaces the above with: String s = new String("YorkLane"); These (convenience) shortcuts make strings "look like" mutable primitive types.

  8. More on the + Operator How does the compiler handle x + y ? • If x and y are both numeric, this is the addition operator. • If eitherx or y is a string, this is the concatenation operator. In this case, the other operand is coerced to a string. • Otherwise, there is a syntax error in this expression.

  9. 6.2 String Handling Given a String, invoke: • Accessors • Transformers • Comparators • Numeric/String Converters Note the absence of mutators

  10. String Methods • length() • charAt(int) • substring(int,int) (int) • indexOf(String) (String,int) • toString() and equals() • compareTo() • toUpperCase() and toLowerCase()

  11. Numeric Strings The Wrapper Classes String s = "1020";int number = Integer.parseInt(s); The other way (from number to string) is best handled thru the + operator (see next)

  12. 6.3 Applications Read the four applications in sections 6.3.1-4 and note, in particular, how indexOf and substring can be used to perform pattern lookup/substitution. Here, we will discuss three different applications but they employ the same techniques:

  13. Applications: • SpaceCounterPrompt for, and read, a string from the user. Output the number of spaces in it. • FileSpaceCounterSimilar to the previous one but it gets its input from the file. The user is prompted to enter the filename. • DigitSpellerRead a string from the user and spell out the names of the digits in it, e.g. input "this6is a5 test4" leads to output: "SIX", "FIVE", and "FOUR".

  14. 6.4 Advanced String Handling • Efficiency calls for immutability • A separate class, StringBuffer, was added to handle mutation. • The new class has three mutators:StringBuffer append(anything)StringBuffer insert(int, anything)StringBuffer delete(int, int)

  15. The + Operator & StringBuffer Given two strings x and y, the compiler replaces: String s = x + y; with: String s = new StringBuffer().append(x).append(y).toString();

  16. An array is an ordered list of values 79 87 94 82 67 98 87 81 74 91 Arrays Each value has a numeric index The entire array has a single name 0 1 2 3 4 5 6 7 8 9 scores An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9

  17. A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression scores[2] refers to the value94(the 3rd value in the array) That expression represents a place to store a single integer and can be used wherever an integer variable can be used Arrays

  18. For example, an array element can be assigned a value, printed, or used in a calculation: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println("Top = " + scores[5]); Arrays

  19. The values held in an array are called array elements An array stores multiple values of the same type (the element type) The element type can be a primitive type or an object reference Therefore, we can create an array of integers, or an array of characters, or an array ofStringobjects, etc. In Java, the array itself is an object Therefore the name of the array is a object reference variable, and the array itself must be instantiated Arrays

  20. Thescoresarray could be declared as follows: int[] scores = new int[10]; The type of the variablescoresisint[](an array of integers) Note that the type of the array does not specify its size, but each object of that type has a specific size The reference variablescoresis set to a new array object that can hold 10 integers Declaring Arrays

  21. Some examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; Declaring Arrays

  22. Once an array is created, it has a fixed size An index used in an array reference must specify a valid element That is, the index value must be in bounds (0 to N-1) Each array object has a public constant calledlengththat stores the size of the array It is referenced using the array name: scores.length Bounds Checking

  23. The brackets of the array type can be associated with the element type or with the name of the array Therefore the following declarations are equivalent: float[] prices; float prices[]; The first format generally is more readable Alternate Array Syntax

  24. An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'}; Initializer Lists

  25. Note that when an initializer list is used: thenewoperator is not used no size value is specified The size of the array is determined by the number of items in the initializer list An initializer list can only be used only in the array declaration Initializer Lists

  26. The elements of an array can be object references The following declaration reserves space to store 25 references toStringobjects String[] words = new String[25]; It does NOT create theStringobjects themselves Each object stored in an array must be instantiated separately Arrays of Objects

  27. Objects can have arrays as instance variables Many useful structures can be created with arrays and objects The programmer must determine carefully an organization of data and objects that makes sense for the situation Arrays of Objects

  28. A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns Two-Dimensional Arrays one dimension two dimensions

  29. To be precise, a two-dimensional array in Java is an array of arrays A two-dimensional array is declared by specifying the size of each dimension separately: int[][] scores = new int[12][50]; A two-dimensional array element is referenced using two index values value = scores[3][6] The array stored in one row or column can be specified using one index Two-Dimensional Arrays

  30. An array can have many dimensions If it has more than one dimension, it is called a multidimensional array Each dimension subdivides the previous one into the specified number of elements Each array dimension has its ownlengthconstant Because each dimension is an array of array references, the arrays within one dimension can be of different lengths these are sometimes called ragged arrays Multidimensional Arrays

  31. The signature of themainmethod indicates that it takes an array ofStringobjects as a parameter These values come from command-line arguments that are provided when the interpreter is invoked For example, the following invocation of the interpreter passes an array of threeStringobjects intomain: C:\> java StateEval pennsylvania texas arizona These strings are stored at indexes 0-2 of the parameter Command-Line Arguments

More Related