Docsity

Arrays and Strings - Object Oriented and GUI Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Arrays and Strings - Object Oriented and GUI Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

1

Chapter 4: Arrays and Strings

2

Basics of Arrays

  • Declaration: int myArray []; or int [] myArray;
  • Definition: int [] myArray = new int[10];
  • Accessing: num = myArray[i]; I should be int
  • Array bound check!!!
  • Array length: myArray.length
  • Initializing:
    • Using assignment statements
    • Using merged declaration and initialization: int myArray = {1, 2, 3};
    • Using a for loop or collection-based for loop:
      • for (declared variable : array name) {………}
    • Using the fill method: Array.fill(arrayname, value); The Array class is found in the util package

4

  • String Literals: “This is a string”
  • Declare String: String myString;
  • Initialize String: String myString = “My String”;
  • Arrays of Strings: String [] names = new String[5];
  • String concatenation: JoinStrings.java
  • String matching: MatchStrings.java & Identity! MatchStrings2.java
  • String comparison: SequenceString.java
  • String searching: FindCharacters.java
  • Extracting Strings: ExtractSubstring.java

Strings

5

  • It is a class that looks like the String class but it is not a static one (its objects are mutable)
  • Operations such (concat., etc.) are much more efficient using StringBuffer
  • Default capacity is 16: StringBuffer buffer = new StringBuffer();
  • Methods: length(), capacity(), setLength()
  • To concatenate use append() (check java doc.)
  • To insert use insert() : buf.insert(5, “ttt”);
  • To convert to String object use toString()
  • Example: UseStringBuffer.java

StringBuffer Class