38
1 String classes and its methods http:// improvejava.blogspot.in

String classes and its methods.20

  • View
    1.971

  • Download
    0

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: String classes and its methods.20

1

String classes and its methods

http://improvejava.blogspot.in

Page 2: String classes and its methods.20

http://improvejava.blogspot.in

Objectives

On completion of this period, you would be able to know

• String class• Methods of String class

Page 3: String classes and its methods.20

3

In 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

1000 1001 1002 1003 1004

Recap

‘r’ ‘a’ ‘m’ ‘u’ ‘\0’

http://improvejava.blogspot.in

Page 4: String classes and its methods.20

4

• 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

String Class

http://improvejava.blogspot.in

Page 5: String classes and its methods.20

5

• 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

String Class contd..

http://improvejava.blogspot.in

Page 6: String classes and its methods.20

6

• 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

String Class

http://improvejava.blogspot.in

Page 7: String classes and its methods.20

7

Strings can be constructed a variety of ways. The easiest is to use a statement like this

String s = “ Good Morning ”;

s

s is the reference Fig 30.1

String Class contd..

“Good Morning”

http://improvejava.blogspot.in

Page 8: String classes and its methods.20

8

• 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

String Class contd..

http://improvejava.blogspot.in

Page 9: String classes and its methods.20

9

• For example, this statement

String cname = “ govt ” + “polytechnic” ;

results in cname containing “govt polytechnic“

• The following program demonstrates the preceding concepts

String Class contd..

http://improvejava.blogspot.in

Page 10: String classes and its methods.20

10

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”); } // end of main method

} // end of class

Output : one two one and two

http://improvejava.blogspot.in

Page 11: String classes and its methods.20

11

• 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);

String Class contd..

http://improvejava.blogspot.in

Page 12: String classes and its methods.20

12

Example program class StringDemo2 {

public static void main(String args[]) {

String str1 = “one”;

String str2 = “two”;

String str3 = str1;

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”);

}

}

Output : length of str1 : 3 char at index 2: n str1 != str2 str1 == str3

http://improvejava.blogspot.in

Page 13: String classes and its methods.20

13

• 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

The String Constructors

http://improvejava.blogspot.in

Page 14: String classes and its methods.20

14

• 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”

The String Constructors contd..

http://improvejava.blogspot.in

Page 15: String classes and its methods.20

15

• 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

The String Constructors contd..

http://improvejava.blogspot.in

Page 16: String classes and its methods.20

16

• 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

The String Constructors Contd..

http://improvejava.blogspot.in

Page 17: String classes and its methods.20

17

• 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());

The String Methods

http://improvejava.blogspot.in

Page 18: String classes and its methods.20

CM602.32 18

• 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()

The String methods Contd..

class A { public String toString() { return “hello”; }}

class B { public static void main (String args[]) { A a = new A(); String s = “hai” + a; System.out.println(s); } }

http://improvejava.blogspot.in

Page 19: String classes and its methods.20

19

• 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

The String Methods contd..

http://improvejava.blogspot.in

Page 20: String classes and its methods.20

20

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);

The String Methods contd..

http://improvejava.blogspot.in

Page 21: String classes and its methods.20

21

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()

The String Methods contd..

http://improvejava.blogspot.in

Page 22: String classes and its methods.20

22

• The String class includes several methods that compare strings or substrings within strings

equals( )

• 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

String Comparison

http://improvejava.blogspot.in

Page 23: String classes and its methods.20

23

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

String Comparison contd..

http://improvejava.blogspot.in

Page 24: String classes and its methods.20

24

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));

}}

String comparison contd..

http://improvejava.blogspot.in

Page 25: String classes and its methods.20

25

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)

String Comparison contd..

http://improvejava.blogspot.in

Page 26: String classes and its methods.20

26

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”)

String Comparison contd..

http://improvejava.blogspot.in

Page 27: String classes and its methods.20

27

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);

} }

String Comparison contd..

http://improvejava.blogspot.in

Page 28: String classes and its methods.20

28

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

String Comparison contd..

http://improvejava.blogspot.in

Page 29: String classes and its methods.20

29

• 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

Searching Strings

http://improvejava.blogspot.in

Page 30: String classes and its methods.20

30

• 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

Searching Strings contd..

http://improvejava.blogspot.in

Page 31: String classes and its methods.20

31

• 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 formsint indexOf(int ch, int startIndex)int lastIndexOf(int ch, int startIndex)

int indexOf(String str, int startIndex)int lastIndexOf(String str, int startIndex)

Searching Strings contd..

http://improvejava.blogspot.in

Page 32: String classes and its methods.20

32

replace() - replaces all occurrences of one character in the invoking string

String replace(char original, char replacement)String subString(int startIndex, int endIndex)

trim() - returns a copy of the invoking string from which any leading and trailing white space has been removed

String trim()

Modifying a String

http://improvejava.blogspot.in

Page 33: String classes and its methods.20

33

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()

Changing the case of characters within a String

http://improvejava.blogspot.in

Page 34: String classes and its methods.20

34

Summary

• We discussed

• String classes

• Uses of string class

• Syntax of string class

• Constructors of String class

• Methods of String class

http://improvejava.blogspot.in

Page 35: String classes and its methods.20

1. Write a class that has String types and also that uses various String methods to perform operations on the above data

Assignment

http://improvejava.blogspot.in

Page 36: String classes and its methods.20

1. String are

a. mutable

b. immutable

c. none

36

Quiz

http://improvejava.blogspot.in

Page 37: String classes and its methods.20

Quiz contd..

2. String is

a. variable

b. class

c. data type

d. none

http://improvejava.blogspot.in

Page 38: String classes and its methods.20

1. Explain the use String class

2. Differentiate String and StringBuffer classes

3. Explain various methods in String class with example programs

38

Frequently Asked Questions

http://improvejava.blogspot.in