Presentation is loading. Please wait.

Presentation is loading. Please wait.

String Objects & its Methods

Similar presentations


Presentation on theme: "String Objects & its Methods"— Presentation transcript:

1 String Objects & its Methods
String variables are actually objects. The String class is unique because String objects can be created by simply declare a String variable. The reference variable knows the address of the String object. The object is assigned a value of whatever characters make up the String literal.

2 Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as a type to declare an object reference variable String title; No object is created with this declaration An object reference variable holds the address of an object The object itself must be created separately A variable can hold either a primitive value or a reference to an object Like variable that hold primitive types, a variable that holds an object reference must be declared. A class is used to define an object (remember that a class is like the blueprint for the object) and the class name can be thought of as the type of an object. The declaration of object references are structured like the declaration of primitive variables.

3 Creating an object is called instantiation
Generally, we use the new operator to create an object title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object Creating an object is called instantiation An object is an instance of a particular class

4 title = "Java Software Solutions";
The String Class Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; This is special syntax that works only for strings Once an object has been instantiated, we can use the dot operator to invoke its methods title.length() Strings in Java are objects represented by the String class. Once a String object is created, its value cannot be lengthened or shorted, nor can any of its characters change. Thus we say that a String object is immutable. We can, however, create new String objects that have the new version of the original string’s value.

5 String Methods The String class has several methods that are useful for manipulating strings Many of the methods return a value, such as an integer or a new String object

6 Make a String object & Assign a value
String variables are actually objects. String myName = new String (“Mrs. Rush”); // myName is Mrs. Rush

7 Create an empty string String yourName = new String(); //yourName is an empty string Uses an empty constructor from the String class A value exists It is not null There are no characters in the String literal Has a value of “” It has a length of 0 characters A null string is a string that has no value and no length. It does not hold an address of a String object. An empty string is a string that has a value of “” and its length is zero. There is no space inside of the double quotation marks because the string is empty. It may seems like an null string and an empty string are the same thing, but they are not. The difference is subtle. The empty string has a value and the null string does not. Furthermore, you can perform a method on an empty string, but you cannot perform a method on a null string. Any attempt to execute a method on a null string will result in a run-time error called a NullPointerException.

8 Create a null string String theirName; //theirName is null
Create a String reference but not a String object Assigned value is null (there isn’t an address of a String object for it to hold) A null string is a string that has: No value No length No address You cannot perform a method on a null string but you can on an empty string. Any attempt to execute a method on a null string will result in a run-time error called a NullPointerExpection.

9 String Object String myName = “Mrs. Rush”;
The numbers represent the index of each character in the String object. M r s . R u h 1 2 3 4 5 6 7 8 This is a visual representation of what a string looks like in memory. The numbers below the characters are called the indices (plural of index) of the string. Each index represents the location of where each of the characters lives with the string. Notice that the first index is zero. An example of how we read this is: the character at index 5 of myName is the character “R”. Also, spaces count as characters. You can see that the character at index 4 is the space character.

10 Equals method The .equals method returns a Boolean answer of true if the two strings are identical and it returns false if the two strings differ in any way. String username1 = “Cat Lady”; String username2 = “cat lady”; System.out.println(username1.equals(“Cat Lady”)); //prints true System.out.println(username2.equals(“Cat Lady”)); //prints false The equals method returns a Boolean answer of true if the two strings are identical and it returns an answer of false if the two strings different in any way. The equals method is case sensitive Never use the == to compare strings. The == equality operator is used to compare numeric values and when used with strings it compares whether or not the two String references pint to the same object. The ! (not operator) can be used with the equals method to determine is two Strings are not equal

11 Equals method String pet1 = “Cat”; String pet2 = “Dog”;
System.out.println(!pet1.equals(pet2)); //prints true

12 Compareto method The .compareTo method returns an integer (positive number, negative number, or zero) This integer describes how the two strings are ordered lexicographically The second way to compare two strings is to use the compareTo method. Instead of returns an answer that is a Boolean like the equals method did, the compreTo method returns an integer. The result of the compareTo method is appositive number, a negative number, or zero. This integer describes how to the two strings are ordered lexicographically. Lexicographically is a case-sensitive ordering of words similar to a dictionary but using the UNICODE codes of each character.

13 String string1 = “Hello”; String string2 = “Hello”; String string3 = “Kitty”; int result = string1.compareTo(string2); // result is 0 because they are exactly same int result2 = string1.compareTo(string3); // result is negative when string1 comes before string3 int result3 = string3.compareTo(string1); // result is positive when string1 comes after the string3

14 Length method The length method returns the number of characters in the specified string (including spaces) String tweet=“I’m going to rock this AP CS exam.”; int return = tweet.length(); //result is 34 String pokemonCard = new String(); int result = pokemonCard.length(); // result is 0

15 String pokemonCard; // No String created int result = pokemonCard
String pokemonCard; // No String created int result = pokemonCard.length(); //error: NullPointerException

16 Indexof Method To find if a string contains a specific character or group of characters, use the indexOf method. It searches the string and if it locates what you are looking for, it returns the index of its location. String sport = “Soccer”; int result = sport.indexOf(“e”); // result is 4 Int result1 = sport.indexOf(“c”); // result is 2 (finds the first “c”) Remember that the index position starts at 0

17 String sport = “Soccer”;
int result = sport.indexOf(“i”); // result is -1 Find the index of a string inside of a string: String findMe = “ce”; int result = sport.indexOf(findMe); // result is 3

18 Substring method The substring method is used to extract a specific character or group of characters from a string. The substring method is overloaded meaning that there is more than one version of the method. Overloaded Method Description substring (int index) Starts extracting at index and stops extracting when it reaches the last character in the string substring (int firstIndex, int secondIndex) Starts extracting at firstIndex and stops extracting at secondIndex -1

19 Extract every character starting at a specified index from a string
String motto = “May the force be with you.”; String result = motto.substring(14); // result is “be with you.”

20 Extract one character from a string
String motto = “May the force be with you.”; String result = motto.substring(2,3); // result is “y”

21 Extract two characters from a string
String motto = “May the force be with you.”; String result = motto.substring(5,7); // result is “he”

22 Extract the word “force” from a string
String motto = “May the force be with you.”; String result = motto.substring(8,13); // result is “force”

23 Use numbers that don’t make any sense:
String motto = “May the force be with you.”; String result = motto.substring(72); // error: StringIndexOutOfBoundsExpection

24 Tolowercase method Returns a new string that is the same as this string except all uppercase letters are changed to lowercase String favTeacher = “Mrs. Rush is my favorite teacher!”; System.out.println(favTeacher.toLowerCase()); mrs. rush is my favorite teacher! //printed line

25 Touppercase method Returns a new string that is the same of this string except all lowercase letters are changed to uppercase letter. String favTeacher = “Mrs. Rush is my favorite teacher!”; System.out.println(favTeacher.toUpperCase()); MRS. RUSH IS MY FAVORITE TEACHER! //printed line

26 review Consider the following code segment:
String newString = “Welcome”; String anotherString = “Home”; newString = anotherString + “Hello”; What is printed as a result of executing this code segment? HomeHello HelloHello WelcomeHello Welcome Hello Home Hello A

27 Which of the following returns the last character of the string str.
str.substring(0); str.substring(0, str.length()); str.substring(length(str)); str.substring(str.length() -1); str.substring(str.length()); d


Download ppt "String Objects & its Methods"

Similar presentations


Ads by Google