String classes and its methods.20
Upcoming SlideShare
Loading in...5

String classes and its methods.20






Total Views
Views on SlideShare
Embed Views



2 Embeds 16 15 1



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
  • thank you
    Are you sure you want to
    Your message goes here
  • was informative. thanks.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

String classes and its methods.20 String classes and its methods.20 Presentation Transcript

  • String classes and its methods 1
  • ObjectivesOn completion of this period, you would be able to know • String class • Methods of String class
  • RecapIn C / C++ • String is collection of characters • It should be declared like a character array of some size • Every string ends with a null ( ‘0’ ) character • Memory is allocated sequentially because it is array eg. : char name[5]; strcpy(name,”ramu”); [0] [1] [2] [3] [4] name ‘r’ ‘a’ ‘m’ ‘u’ ‘0’ 1000 1001 1002 1003 1004 3
  • String Class• String is probably the most commonly used class in java’ class• Strings are very important part of programming• Every string you create is actually an object of type String• Even string constants are actually String objects• Java language provides a system defined class String in the java.lang package 4
  • String Class contd..• For example: in the statement System.out.println(“ this is a string ”);• The string “ this is a string ” is a String constant• Java handles String constants in the same way that other computer languages handle “normal” strings 5
  • String Class• The objects of type Strings are immutable• Once a String is created, its contents cannot be altered• This may seem like a serious restriction but we have the following advantages with this • If you need to change a string, you can always create a new one that contains the modifications • Java defines a peer class of String, called StringBuffer, which allows strings to be altered 6
  • String Class contd..Strings can be constructed a variety of ways. The easiest is to use a statement like this String s = “ Good Morning ”; “Good Morning” s s is the reference Fig 30.1 7
  • String Class contd..• Once you have created a String object, you can use it anywhere that a string is allowed• For example, this statement displays cname System.out.println(cname);• Java defines ‘+’ operator for String objects• It is used to concatenate two strings 8
  • String Class contd..• For example, this statement String cname = “ govt ” + “polytechnic” ; results in cname containing “govt polytechnic“• The following program demonstrates the preceding concepts 9
  • Example Program: String Class// Demonstrating Stringsclass StringDemo { public static void main(String args[]) { String str1 = “one”; String str2 = “two” String str3 = str1 + “ and ” + str2’; System.out.println(“ str1 ”); System.out.println(“ str2”); System.out.println(“ str3”); Output : } // end of main method one two} // end of class one and two 10
  • String Class contd..• String class contains several methods that you can use • test two strings for equality by using equals() boolean equals(String object); • obtain the length of a string by calling the length(). int length(); • Obtain the character at a specified index within a string by calling charAt() char charAT(int index); 11
  • Example programclass StringDemo2 { public static void main(String args[]) { Output : String str1 = “one”; length of str1 : 3 char at index 2: n String str2 = “two”; str1 != str2 String str3 = str1; str1 == str3 System.out.println(“ length of str1 : ”+str1.length()); System.out.println(“ char at index 2 in str1 : ”+str1.charAt(2)); if(str1.equals(str2)) { System.out.println(“ str1 == str2”); else System.out.println(“ str1 != str2”); if(str1.equals(str3)) { System.out.println(“ str1 == str3”); else System.out.println(“ str1 != str3”); }} 12
  • The String Constructors• To create an empty String, you call the default constructor. For example String s = new String():• will create an instance of String with no characters in it• String class has also parameterized constructors• If you want to create strings that have initial values. The string class provides a variety of constructors to handle this 13
  • The String Constructors contd..• To create an empty String initialized by an array of characters, use the constructor shown here String(char chars[] ) eg. char chars[] = {‘a’, ‘b’, ’c’ }; String s = new String(chars); The constructor initializes s with the string “abc” 14
  • The String Constructors contd..• You can specify a subrange of a character array as an initializer using the following constructor String(char chars[] , int startIndex, int numChars) here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use eg. char chars[] = {‘a’, ‘b’, ’c’ ,’d’, ’e’, ’f’}; String s = new String(chars,2,3); this initializes s with the characters cde 15
  • The String Constructors Contd..• You can construct a String object that contains the same character sequence as another String object using the following constructor String(String strObj) here, strObj is a String object eg. char chars[] = {‘a’, ‘b’, ’c’ ,’d’, ’e’, ’f’}; String s1 = new String(chars); String s2 = new String(s1); String objects s1 and s2 contains same String 16
  • The String Methods• String length • The length of a string is the number of characters that it contains. To obtain this value, call the length() method int length() • The following fragment prints “3”, since there are three characters in the string s; char chars[] = {‘ a ’, ‘ b ’, ‘ c ’}; String s = new String(chars); System.out.println(s.length()); or System.out.println(“abc”.length()); 17
  • The String methods Contd..• toString() : • Every class implements toString() because it is defined by Object • However, the default implementation of toString() is seldom sufficient • The general form of toString() method is String toString() class A { class B { public String toString() { public static void main (String return “hello”; args[]) { } A a = new A(); } String s = “hai” + a; System.out.println(s); } } CM602.32 18
  • The String Methods contd..• Character extraction • The String class provides a number of ways in which characters can be extracted from a String object. • The string index begins at zero char charAt() : to extract a single character from a String char ch; ch =“abc”.charAt(1) assigns the value “b” to ch 19
  • The String Methods contd..getChars() If you need to extract more than one character at a time, you can use the getchars() method, it has this general form void getChars(int soureStart, int sourceEnd, char target[], int targetStart) String s = “government polytechnic warangal”; int start = 10; int end = 14; char buf[] = new char[end-start]; s.getShars(start, end,buf,0); System.out.println(buf); 20
  • The String Methods contd..getBytes()• It is alternative to getChars() that stores the characters in an array of bytes byte[] getBytes()toCharArray()• It returns an array of characters for the entire string char[] toCharArray() 21
  • String Comparison• The String class includes several methods that compare strings or substrings within stringsequals( )• two compare two strings for equality, use equals() boolean equals(Object str)• Here, str is the string object being compared with the invoking String object 22
  • String Comparison contd..equalsIgnoreCase( )• To perform a comparison that ignores case differences boolean equalsIgnoreCase(String str)• when it compares two strings, it considers A – Z to be the same as a – z• here, str is the String object being compared with the invoking String object 23
  • String comparison contd..class A { public static void main(String args[]) { String s1 = “hello”; String s2 = “hello”; String s3 = “HELLO”; System.out.println(s1.equals(s2)); System.out.println(s1.equals(s3)); System.out.println(s1.equalsIgnoreCase(s3)); }} 24
  • String Comparison contd..regionMatches( )• Compares a specific region inside a string with another specific region in another string• There is an overloaded form that allows you to ignore case in such comparison boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars) boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars) 25
  • String Comparison contd..startsWith( )• Determines whether a given String begins with a specified string boolean startsWith(String str) eg: “Foobar”.startsWith(“Foo”)endsWith( )• Determines whether a given String ends with a specified string boolean endsWith(String str) eg: “Foobar”.startsWith(“Foo”) 26
  • String Comparison contd..equals ( ) versus ==• equals() methods compares the characters inside a String object = = operator compares two object references to see whether they refer to the same instance class A { public static void main(String args[]) { String s1 = “Hello”; String s2 = new String(s1); System.out.println(s1.equals(s2)); System.out.println(s1==s2); } } 27
  • String Comparison contd..compareTo( )• Used to know two strings are identical, less than, or greater than the next• A string is less than another if it comes before the other in dictionary order• A string is greater than another if it comes after the other in dictionary order int compareTo(String str)• Here, str is the string being compared with the invoking String 28
  • Searching Strings• The String class provides two methods that allow you to search a string for a specified character or substring indexOf() - searches for the first occurrence of a character or substring. lastIndexOf() - searches for the last occurrence of a character or substring• These two methods are overloaded in several different ways. In all cases , the methods return the index at which the charcter or substring was found or -1 returned on failure 29
  • Searching Strings contd..• To search for the first occurrence of a character, use int indexOf(int ch)• To search for the last occurrence of a character, use int lastIndexOf(int ch)• Here, ch is the character being sought 30
  • Searching Strings contd..• To search for the first or last occurrence of a substring, use int indexOf(String str) int lastIndexOf(String str)• Here, str specifies the substring• You can specify a starting point for the search using these forms int indexOf(int ch, int startIndex) int lastIndexOf(int ch, int startIndex) int indexOf(String str, int startIndex) int lastIndexOf(String str, int startIndex) 31
  • Modifying a Stringreplace() - replaces all occurrences of one character in theinvoking string String replace(char original, char replacement) String subString(int startIndex, int endIndex)trim() - returns a copy of the invoking string from which anyleading and trailing white space has been removed String trim() 32
  • Changing the case of characters within a String toLowerCase() - converts all the characters in a string from uppercase to lowercase String toLowerCase() toUpperCase() - converts all the characters in a string from lowercase to uppercase String toUpperCase() 33
  • Summary• We discussed • String classes • Uses of string class • Syntax of string class • Constructors of String class • Methods of String class 34
  • Assignment1. Write a class that has String types and also that uses various String methods to perform operations on the above data
  • Quiz1. String are a. mutable b. immutable c. none 36
  • Quiz contd..2. String is a. variable b. class c. data type d. none
  • Frequently Asked Questions1. Explain the use String class2. Differentiate String and StringBuffer classes3. Explain various methods in String class with example programs 38