Strings
Sponsored Links
This presentation is the property of its rightful owner.
1 / 28

Strings PowerPoint PPT Presentation


  • 143 Views
  • Uploaded on
  • Presentation posted in: General

Strings. Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts. Topics :. literal strings String constructors immutability of strings String comparisons Substrings String concatenation Other commonly used methods toString () method on Objects.

Download Presentation

Strings

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Strings

Carol Yarbrough

AP Computer Science Instructor

Alabama School of Fine Arts


Topics:

  • literal strings

  • String constructors

  • immutability of strings

  • String comparisons

  • Substrings

  • String concatenation

  • Other commonly used methods

  • toString() method on Objects


String class facts

  • An object of the String class represents a string of characters.

  • The String class belongs to the java.lang package, which does not require an import statement.

  • Like other classes, String has constructors and methods.

  • Unlike other classes, String has two operators, + and += (used for concatenation).

  • Strings are immutable


Strings

  • Strings are objects, and thus references

  • String s;// no string

  • String s = new String("Hi");// string

  • String s = "Hi";// string

  • String s = "";// string


Literal Strings

  • are anonymous objects of the String class

  • are defined by enclosing text in double quotes. “This is a literal String”

  • don’t have to be constructed.

  • can be assigned to String variables.

  • can be passed to methods and constructors as parameters.

  • have methods you can call.


Literal String examples

//assign a literal to a String variable

String name = “Robert”;

//assign literals with escape sequences

String twoLine = “first \nsecond line”;

String quote = " He said, \" Yes\".";

String bksl = “This is backslash: \\”;

//calling a method on a literal String

char firstInitial = “Robert”.charAt(0);

//calling a method on a String variable

char firstInitial = name.charAt(0);


Immutability

  • Once created, a string cannot be changed: none of its methods changes the string.

  • Such objects are called immutable.

  • Immutable objects are convenient because several 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.


“Java"

“Java"

“Java"

Advantages Of Immutability

Uses less memory.

String word1 = "Java";

String word2 = word1;

String word1 = “Java";

String word2 = new String(word1);

word1

word1

word2

word2

Less efficient: wastes memory

OK


“java"

“Java"

Disadvantages of Immutability

Less efficient — you need to create a new string and throw away the old one even for small changes.

String word = “java";

char ch = Character.toUpperCase(word.charAt (0));

word = ch + word.substring (1);

word


Empty Strings

  • An empty String has no characters. It’s length is 0.

  • Not the same as an uninitialized String.

Empty strings

String word1 = "";

String word2 = new String();

errorMsg is null

private String errorMsg;


Changing String Values

  • Strings have no methods to let you change an existing character in a string.

    • To change a string you have to reassign the variable to a new string.

    • example:

      • String greeting = “Hello”;greeting = greeting.substring(0,4) + “!”;

      • Result: greeting is now “Hell!”


Comparing String Values

  • Because String variables hold memory addresses, you cannot make a simple comparison of the contents

  • The String class provides a number of methods

    • equals() method

    • equalsIgnoreCase() method

    • compareTo() method


Comparing String Values

  • equals() method- Evaluates the contents of two String objects to determine if they are equivalent

    • This method returns true if the two String objects have identical contents

    • Can take either a variable String object or a literal string as its argument

      • s1.equals(s2);

      • s1.equals(“Hello”);


Comparing String Values

  • compareTo() method- Used to compare two Strings

    • Returns zero only if the two Strings hold the same value

    • If there is any difference between the Strings, a negative number is returned if the calling object is “less than” the argument

    • A positive number is returned if the calling object is “more than” the argument

    • Strings are considered “less than” or “more than” each other based on their Unicode values


String Equality

String s1 = new String("Hi");

String s2 = new String("Hi");

System.out.println( s1 == s2 ); // false

System.out.println( s1.equals(s2) ); // true

"Hi"

s1

String reference

"Hi"

s2

String reference


String Equality

String s1 = new String("Hi");

String s2 = s1;

System.out.println( s1 == s2 );// true

System.out.println( s1.equals(s2) ); // true

"Hi"

s1

String reference

s2

String reference


String Equality

String s1 = "Hi";

String s2 = "Hi";

System.out.println( s1 == s2 );// true

System.out.println( s1.equals(s2) ); // true

"Hi"

s1

String reference

s2

String reference


String Equality

String s1 = "Hi";

String s2 = "H" + "i"; // evaluated during compile

System.out.println( s1 == s2 );// true

System.out.println( s1.equals(s2) ); // true

"Hi"

s1

String reference

s2

String reference


Methods — substring

  • String subs = word.substring (i, k);

    • returns the substring of chars in positions from i to k-1

  • String subs = word.substring(i);

    • returns the substring from the i-th char to the end

Returns a new String by copying characters from an existing String.

television

i k

television

i

Returns:

“lev"

“mutable"

"" (empty string)

”television".substring (2,5);

“immutable".substring (2);

“bob".substring(3);


Methods — Concatenation

String word1 = “re”, word2 = “think”; word3 = “ing”;

int num = 2;

  • String result = word1 + word2;

    //concatenates word1 and word2 “rethink“

  • String result = word1.concat (word2);

    //the same as word1 + word2 “rethink“

  • result+= word3;

    //concatenates word3 to result “rethinking”

  • result += num; //converts num to String//and concatenates it to result “rethinking2”


Methods — Find (indexOf)

0 2 6 10 15

String name =“President George Washington";

name.indexOf(‘P'); 0

name.indexOf(‘e'); 2

name.indexOf(“George"); 10

name.indexOf(‘e', 3); 6

name.indexOf(“Bob"); -1

name.lastIndexOf(‘e'); 15

Returns:

(starts searching at position 3)

(not found)


Using Other String Methods

  • There are additional String methods available in the String class

    • toUpperCase() and toLowerCase() convert any String to its uppercase or lowercase equivalent

    • the String class contains many other useful methods (see java.sun.com)


Some Other String Methods


Object.toString()

  • Every class implements toString( ) because it is defined by Object.

  • The default implementation of toString( ) is seldom sufficient.

  • Most classes override toString( ) and provide string representations.

  • Fortunately, this is easy to do.


String toString( )

  • To implement toString( ), simply return a String object that contains a string that describes an object of your class.

  • By overriding toString( ), you allow the resulting strings to be used in print( ) and println( ) statements and in concatenation expressions.


toString() Example

  • // Override toString() for Box class. class Box { double width, height, depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } public String toString() { return "Dimensions are " + width + " by " + depth + " by " + height + "."; } }


Strings on the AP Exam

  • Strings are an important part of the AP exam.

  • There are, however, few questions strictly about Strings

  • Instead knowledge of Strings is needed to answer questions about sorting, searching and arrays.


A Couple of String Problems

  • 2008 AP exam problems 12, 30 and 40

  • 2008 AP exam Free Response problem 1


  • Login