19
Strings

8[1].Strings

Embed Size (px)

DESCRIPTION

Strings

Citation preview

Page 1: 8[1].Strings

Strings

Page 2: 8[1].Strings

String Class• It is immutable class Available in java.lang

package .• String contain sequences of 16-bit Unicode

characters.• The String class contains an immutable string.

Once an instance is created, the string it contains cannot be changed.

• Most common string constructor:• String s1 = new String(“immutable”); //causes

extra memory allocation for no obvious advantage.• String s1 = “immutable”; //better

• Every string literal is represented internally by an instance of String. Java classes may have a pool of such strings.

Page 3: 8[1].Strings

• There are two ways to create String object:1. By string literal2. By new keyword

1) String literal is created by double quote.For Example: String s="Hello"; Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.For exampleString s1="Welcome"; String s2="Welcome";//no new object will be created ADV: To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

Page 4: 8[1].Strings

2) By new keywordString s=new String("Welcome");

//creates two objects and one reference variableIn such case, JVM will create a new String object in normal (nonpool) Heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in Heap (nonpool).

Why string objects are immutable in java?Because java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

Page 5: 8[1].Strings

String Class• Because String is immutable, modifying it is

very expensive, StringBuffer may be the better solution.

String s = “ 5 + 4 = 20”;2. s = s.trim(); // “5 + 4 = 20”3. s = s.replace(‘+’, ‘x’);

Page 6: 8[1].Strings

String comparison• We can compare two given strings on the basis of content and

reference.• It is used in authentication (by equals() method),sorting (by

compareTo() method), reference matching (by == operator) etc.• There are three ways to compare String objects:

1. By equals() method2. By = = operator3. By compareTo() method

• equals() method compares the original content of the string. It compares values of string for equality

• The = = operator compares references not values.• compareTo() method compares values and returns an int which

tells if the values compare less than, equal, or greater than• s1 == s2 :0, s1 > s2 :positive value, s1 < s2:negative value

Page 7: 8[1].Strings

Example:class Simple{ public static void main(String args[]){ String s1="Sachin"; String s2="Sachin"; String s3=new String("Sachin"); String s4="Saurav"; System.out.println(s1.equals(s2));//true System.out.println(s1.equals(s3));//true System.out.println(s1.equals(s4));//false

System.out.println(s1==s2);//true (because both refer to same instance) System.out.println(s1==s3);//false(because s3 refers to instance in nonpool)

System.out.println(s1.compareTo(s2));//0 System.out.println(s1.compareTo(s4));//non zero

} }

Page 8: 8[1].Strings

String Concatenation• Concatenation of strings form a new string i.e. the combination of multiple strings.• There are two ways to concat string objects:

1. By + (string concatenation) operator2. By concat() method

• Example:class Simple{ public static void main(String args[]){ String s="Sachin"+" Tendulkar"; System.out.println(s); //Sachin Tendulkar

String s1="Sachin "; String s2="Tendulkar"; String s3=s1.concat(s2); System.out.println(s3); //Sachin Tendulkar } }

Page 9: 8[1].Strings

Other String class methodsMethod Description

1)public boolean equals(Object anObject)

Compares this string to the specified object.

2)public boolean equalsIgnoreCase(String another)

Compares this String to another String, ignoring case.

3)public String concat(String str) Concatenates the specified string to the end of this string.

4)public int compareTo(String str) Compares two strings and returns int

5)public int compareToIgnoreCase(String str)

Compares two strings, ignoring case differences.

6)public String substring(int beginIndex)

Returns a new string that is a substring of this string.

7)public String substring(int beginIndex,int endIndex)

Returns a new string that is a substring of this string.

8)public String toUpperCase() Converts all of the characters in this String to upper case

Page 10: 8[1].Strings

9)public String toLowerCase() Converts all of the characters in this String to lower case.

10)public String trim() Returns a copy of the string, with leading and trailing whitespace omitted.

11)public boolean startsWith(String prefix) Tests if this string starts with the specified prefix.

12)public boolean endsWith(String suffix) Tests if this string ends with the specified suffix.

13)public char charAt(int index) Returns the char value at the specified index.

14)public int length() Returns the length of this string.

15)public String intern() Returns a canonical representation for the string object.

16)public byte[] getBytes() Converts string into byte array.

17)public char[] toCharArray() Converts string into char array.

18)public static String valueOf(int i) converts the int into String.

19)public static String valueOf(long i) converts the long into String.

20)public static String valueOf(float i) converts the float into String.

21)public static String valueOf(char[] i) converts the char array into String.

22)public static String valueOf(Object obj) converts the Object into String.

23)public void replaceAll (String firstString, String secondString)

Changes the firstString with secondString.

Page 11: 8[1].Strings

String Buffer class • StringBuffer class represents a string

that can be dynamically modified (mutable string). It contain sequences of 16-bit Unicode characters.

• Constructors: StringBuffer() - create an empty

buffer StringBuffer(int length) -

create an empty buffer with a initial capacity

StringBuffer (String str)• Modification operations: append,

insert, reverse, setCharAt and setLength

Page 12: 8[1].Strings

String Buffer class (cont.) • How StringBuffer is modified?

1. StringBuffer sbuf = new StringBuffer(“12345”);2. sbuf.reverse(); // “54321”3. sbuf.insert(3, “aaa”); // “543aaa21”4. sbuf.append(“zzz”); // “543aaa21zzz”

Page 13: 8[1].Strings

1

String Buffer class (cont.) • Use toString() to returns the encapsulated

string in StringBuffer object.• The concat() method of the String class and

the append() method of the StringBuffer class glue two strings together. An easier way to concatenate strings is to use Java’s overloaded + operator.

• Example: a + b + cThe Java compiler treats the code above as if

it were the following:New

StringBuffer().append(a).append(b).append(c).toString();

Page 14: 8[1].Strings

String buffer methods1. public synchronized StringBuffer append(String s): is used to append the

specified string with this string. 2. public synchronized StringBuffer insert(int offset, String s): is used to insert

the specified string with this string at the specified position. 3. public synchronized StringBuffer replace(int startIndex, int endIndex, String

str): is used to replace the string from specified startIndex and endIndex.4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used

to delete the string from specified startIndex and endIndex.5. public synchronized StringBuffer reverse(): is used to reverse the string.6. public int capacity(): is used to return the current capacity.7. public void ensureCapacity(int minimumCapacity): is used to ensure the

capacity at least equal to the given minimum.8. public char charAt(int index): is used to return the character at the specified

position.9. public String substring(int beginIndex): is used to return the substring from

the specified beginIndex.10. public String substring(int beginIndex, int endIndex): is used to return the

substring from the specified beginIndex and endIndex.

Page 15: 8[1].Strings

1

StringBuilder

StringBuffer class is synchronized (thread-safe) i.e. multiple threads cannot access it simultaneously .So it is safe and will result in an order.

A mutable sequence of characters. This class is similar to StringBuffer, but Its methods are not synchronized.

If Synchronization is not required then use StringBuilder. It will be faster.

Page 16: 8[1].Strings

String Tokenizer• The java.util.StringTokenizer class allows you to break a string

into tokens. It is simple way to break string.• It doesn't provide the facility to differentiate numbers, quoted

strings, identifiers etc.• There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str, String delim)

creates StringTokenizer with specified string and delimeter.

StringTokenizer(String str, String delim, boolean returnValue)

creates StringTokenizer with specified string, delimeter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.

Page 17: 8[1].Strings

Methods of string tokenizer classPublic method Description

boolean hasMoreTokens() checks if there is more tokens available.

String nextToken() returns the next token from the StringTokenizer object.

String nextToken(String delim) returns the next token based on the delimeter.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.

Page 18: 8[1].Strings

Example:import java.util.StringTokenizer;

public class Simple{ public static void main(String args[]){ StringTokenizer st = new StringTokenizer("my,name is, khan); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); // System.out.println("Next token is : " + st.nextToken(",")); } } } NOTE: StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).

Page 19: 8[1].Strings

1

Thank You