Strings - PowerPoint PPT Presentation

About This Presentation
Title:

Strings

Description:

However, strings created with the new keyword are not kept in the pool. ... CarWash cw = new CarWash(); Car[] myCars = new Car[3]; myCars[0] = new Car('Porshe' ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 35
Provided by: IBMU362
Learn more at: http://www.cs.ucf.edu
Category:
Tags: cw | new | strings | the

less

Transcript and Presenter's Notes

Title: Strings


1
Strings
  • A string is a sequence of characters.
  • Java provides two classes to support strings
  • String class the instances of String class are
    constants, ie. the content of a String object
    cannot be changed after its creation AKA
    immutable
  • StringBuffer class the instances of
    StringBuffer class are mutable, ie. the
    content of a StringBuffer object can be changed
    after its creation.
  • The String class has some unique privileges not
    shared by ordinary classes.
  • A string can be created using string literals.
    (i.e. without using new operator)
  • Operator can be applicable to strings.
  • The characters in a string indexed by 0 to n-1,
    where n is the length of the string.

2
String Class
  • Creation of a String object.
  • String s new String(abc)
  • String s abc
  • Add operator
  • String s1 abc
  • String s2 de
  • String s3 s1 s2
  • String class has a lot of methods. These methods
    are useful to manipulate strings.

3
String Literals
  • String literals (e.g. This is a string) or
    string-valued constant expressions (e.g. This is
    a constant expression) are created at
    runtime and stored in a pool.
  • Redundant literals re-use existing String
    objects in the pool.
  • Example
  • String s1 hello
  • String s2 hello
  • System.out.println(s1 s2) // prints true
  • However, strings created with the new keyword are
    not kept in the pool.
  • Example
  • String s1 hello
  • String s2 new String(hello)
  • System.out.println(s1 s2) // prints false

4
length and charAt
  • int length() this instance method returns the
    length of the string.
  • String sabc
  • s.length() ? returns 3
  • char charAt(int index) this instance method
    returns the character at the given index.
  • String sabcde
  • s.length() ? 5
  • s.charAt(0) ? a
  • s.charAt(1) ? b
  • s.charAt(4) ? e
  • s.charAt(5) ? error

5
indexOf
  • int indexOf(char c)
  • int indexOf(char c, int index)
  • Returns the index of the first occurrence of the
    character c in the current object, no less than
    index (default 0). Returns 1 if there is no such
    occurrence.
  • String sababc
  • s.indexOf(b) ? 1
  • s.indexOf(b,2) ? 3
  • int indexOf(String s2)
  • int indexOf(String s2, int index)
  • Returns the index of the first occurrence of the
    string s2 in the current object, no less than
    index (default 0). Returns 1 if there is no such
    occurrence.
  • String sdaabcabc
  • String s2ab
  • s.indexOf(s2) ? 2
  • s.indexOf(s2,3) ? 5

6
substring
  • String substring(int startindex)
  • String substring(int startindex, int lastindex)
  • Returns the substring of the current object
    starting from startindex and ending with
    lastindex-1 (or the last index of the string if
    lastindex is not given)
  • String sabcdef
  • s.substring(1) ? bcdef
  • s.substring(3) ? def
  • s.substring(1,4) ? bcd 
  • s.substring(3,5) ? de 

7
equals and equalsIgnoreCase
  • boolean equals(String s2)
  • boolean equalsIgnoreCase(String s2)
  • Returns true if the current object is equal to
    s2 otherwise false. equalsIgnorecase disregards
    the case of the characters.
  • String sabc
  • s.equals(abc) ? true
  • s.equals(abcd) ? false
  • s.equals(aBc) ? false
  • s.equalsIgnoreCase(aBc) ? true

8
StringBuffer Class
  • StringBuffer constructors
  • StringBuffer()
  • StringBuffer(int size)
  • Returns an instance of the StringBuffer class
    that is empty but has an initial capacity of
    size characters (default 16 characters).
  • StringBuffer(String arg)
  • Creates an instance of the StringBuffer class
    from the string arg.
  • length and charAt methods are also defined for
    StringBuffer class.

9
append and insert
  • StringBuffer append(String s)
  • Returns the current object with the String
    parameter s appended to the end.
  • StringBuffer insert(int index, char c)
  • StringBuffer insert(int index, String s)
  • Inserts the character c (or String s) into the
    current StringBuffer object at index index. The
    characters (after index) are shifted to right.
  • StringBuffer sb new StringBuffer(abcd)
  • sb.insert(0,AB) ? sb is ABabcd
  • sb.insert(1,CD) ? sb is ACDBabcd
  • sb.insert(8,EFG) ? sb is ACDBabcdEFG
  • sb.append(HI) ? sb is ACDBabcdEFGHI

10
Palindrome Example
  • import java.io.
  • public class Palindrome
  • static boolean isPalindrome(String s)
  • int i 0
  • int j s.length() - 1
  • boolean flag true
  • while ((iltj) flag)
  • if (s.charAt(i) ! s.charAt(j))
  • flag false
  • else i j--
  • return flag

11
Converting to a String
  • Objects can return a string representation of
    themselves by calling the toString method.
  • For primitives, we have two ways of converting to
    a String
  • String.valueOf() (static method of the String
    class)
  • Example String.valueOf(5000) produces a String
    object equivalent to 5000
  • Or, we can take advantage of the behavior of the
    operator. Remember than the operator means
    concatenation when one of the two arguments is a
    String
  • Example Hello World ? Hello World
  • Example 5 hello ? 5hello
  • Example 5 ? 5 // can be used instead of
    String.valueOf

12
Arrays
  • An array is an object just like any other object
    in Java!
  • It just has some special syntax (bracket
    notation).

13
Arrays
  • An array is a group of contiguous locations that
    all have the same name and the same type.
  • x
  • x0 x1 x2 x3 x4
    x5
  • Accessing array elements
  • arraynameindex where index is an integer
    expression
  • x02
  • i2
  • xi1xi

5 -2 8 3 -2 7
14
Declaring and Allocating Arrays
  • type arrayname new typearraysize
  • int x
  • x new int8
  • int y new int10
  • type arrayname values
  • int y 1,3,5,8 allocates an integer array
    with size 4 (index range0-3)
  • with initial values.
  • Other Notation type arrayname
  • int x We prefer the first notation because
    it is consistent with
  • other declarations.
  • Array Length arrayname.length
  • x.length ? 8

15
Arrays of Primitives (1)
  • Assume the following declaration
  • char initials
  • After executing declaration we have

initials
(null)
16
Arrays of Primitives (2)
  • Now we execute the line below
  • initials new char4
  • The situation now looks like

initials
initials char
Note Each slot in the array is initialized with
the default value of the type of the slots.
0
\u0000
1
\u0000
2
\u0000
3
\u0000
17
Arrays of Primitives (3)
  • Assume the following line is executed
  • initials1 B
  • Now the array looks like

initials
initials char
0
\u0000
1
B
2
\u0000
3
\u0000
18
Arrays of Objects (1)
  • Assume the following declaration
  • Animal animals
  • After executing declaration we have

animals
(null)
19
Arrays of Objects (2)
  • Assume we have the following declaration and
    assignment
  • Animal animals new Animal4
  • The situation then looks like this

animals
There are no objects bound to the array slots yet!
animals Animal
0
null
1
null
2
null
3
null
20
Arrays of Objects (3)
  • Now assume we execute the following line
  • animals2 new Animal()
  • The array looks like

animals
animals Animal
0
null
1
null
2
Animal
3
null
21
Arrays of Objects - Pitfalls
  • Assume the following code
  • Animal hisPets new Animal2
  • Animal herPets new Animal3
  • Animal fido new Animal(fido)
  • hisPets1 fido
  • herPets0 fido
  • The situation looks like

herPets
hisPets
herPets Animal
hisPets Animal
0
0
null
1
null
Fido Animal
1
2
null
22
Array Element Initialization
  • Many times youll want fill an array with objects
    (instead of leaving the slots null). To
    accomplish this, you can use a for loop. On each
    iteration, instantiate an object and then bind
    that object to the current array slot.
  • for (int i 0 i lt animals.length i)
  • animalsi new Animal()

23
Array Element Usage
  • Array elements are variables that are bound to
    objects. Because of this, we can use array
    elements anywhere an individual variable can be
    used.
  • Example
  • animal2.speak()

24
Array Element Usage
  • Assume the following class definition
  • public class CarWash
  • public void wash(Car c)
  • And the following usage
  • CarWash cw new CarWash()
  • Car myCars new Car3
  • myCars0 new Car(Porshe)
  • myCars1 new Car(BMW)
  • myCars2 new Car(Benz)
  • cw.wash(myCars1) // wash the BMW

25
Aggregate Array Parameters (1)
  • Sometimes, we need to operate on entire arrays.
    Methods can be defined to take entire arrays as
    arguments. Assume the following class
    definition
  • public class CarWash
  • public void washAll(Car c)
  • And the following usage
  • CarWash cw new CarWash()
  • Car myCars new Car3
  • myCars0 new Car(Porshe)
  • myCars1 new Car(BMW)
  • myCars2 new Car(Benz)
  • cw.washAll(myCars) // wash all my cars

26
Aggregate Array Parameters (2)
  • Since arrays are also objects, they are passed
    into methods using call-by-reference.
  • A pointer to the array is passed into the method
    (like in C).
  • The contents of the array pointed to by an actual
    parameter can be changed by the method.
  • static void shiftValuesLeft(int x)
  • int i, temp
  • tempx0
  • for (i0 ilt(x.length-1) i)
  • xixi1
  • xx.length-1temp
  • // in main method of same class
  • int a 3,5,7,8
  • shiftValuesLeft(a) // the content of array a
    will be changed

27
Aggregate Assignment
  • One array can be assigned to another in a single
    statement
  • double array1 new double6
  • double array2 new double5
  • array1 array2
  • array1 becomes bound to whatever array2 was bound
    to. The array to which array1 was originally
    bound is eligible for garbage collection.

28
Boundary Violations
  • Assume the following code
  • Animal animals new Animal4
  • animals4 new Animal()
  • The above code would generate a run-time
    exception of type ArrayIndexOutOfBoundsException

29
Array Examples
  • Reading values of an int array
  • int x new int100
  • for (i0 iltx.length i)
  • System.out.println(Enter an integer )
  • xi Integer.parseInt(stdin.readLine().trim())
  • Shifting values of an int array
  • int temp x0
  • for (i0 iltx.length i)
  • xixi1
  • xx.length-1temp

30
Array Examples (cont.)
  • Finding the location of the maximum value in an
    int array
  • int loc 0
  • for (i1 iltx.length i)
  • if(xigtxloc)
  • loci
  • Finding the first location of a given value in an
    int array
  • int loc, i0
  • while ((iltxlength) (xi!item))
  • ii1
  • if (igtx.length) loc-1 // not found
  • else loci // found

31
Array Examples (cont.)
  • Finding summation of the values in an int array
  • int sum0
  • for (i0 iltx.length i)
  • sumsumxi
  • Reversing the contents of an int array
  • int temp,i,j
  • for (i0,jx.length-1 iltj i, j--)
  • tempxi
  • xixj
  • xjtemp

32
Multi-Dimensional Arrays
  • Allocation of two-dimensional array
  • int x new int53
  • Accessing elements of a two-dimensional array
  • x00 5
  • Initializing a two-dimensional array
  • int a 3,5,7,8,6,9






33
Arrays of Varying Length
  • The size of each row of a two-dimensional array
    can be different
  • int x
  • x new int5
  • x0 new int1
  • x1 new int2
  • x2 new int3
  • x3 new int4
  • x4 new int5
  • x.length ? 5
  • x0.length ? 1
  • x1.length ? 2
  • ? x1 new int10

x











34
Strings and char Arrays
  • Strings in Java are not char arrays (in C and C
    strings are char arrays).
  • But, we convert a char array into a string or a
    string into a char array.
  • char array into string
  • char name m,a,r,k
  • String aname new String(name
  • string into char array
  • String aname mary
  • char name aname.toCharArray()
Write a Comment
User Comments (0)
About PowerShow.com