Download SEF_COJ_3_StringHandling_Ver2

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Software Engineering
Module: Core of Java
Topic : String Handling
TALENTSPRINT | © Copyright 2012
String Handling
The content in this presentation is aimed at teaching
learners to:
• Work on string handling methods
• Convert / Modify the string
• Divide the string into tokens using (StringTokenizer)
TALENTSPRINT | © Copyright 2012
2
String Handling
What is a String in java?
String is a class but not primitive in Java. An object
of the String class represents a string of characters.
String is immutable, which means the value stored
in the String object cannot be changed.
The String class belongs to the java.lang package.
Like other classes, String has constructors and
methods.
TALENTSPRINT | © Copyright 2012
3
String Handling
Creating Strings
String str = "TalentSprint";
The above statement is equivalent to the below:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
Following are some of the ways to instantiate java String:
String str1 = new String("TalentSprint");
String str2 = new String(char []);
String str3 = new String(byte []);
TALENTSPRINT | © Copyright 2012
4
String Handling
What is immutability?
String is immutable, which means the value stored in the
String object cannot be changed.
Then the next question that comes to our mind is:
“If String is immutable then how am I able to change the
contents of the object?”.
Well, to be precise it’s not the same String object that
reflects the changes you do. Internally a new String
object is created to do the changes.
For example declare a String object as below:
String ts = “Talent”;
TALENTSPRINT | © Copyright 2012
5
String Handling
What is immutability?
Next, you want to append “Sprint” to the same String.
ts = ts + ”Sprint”;
When you print the contents of 'ts' the output will be
“TalentSprint”.
Although we made use of the same object(ts), internally
a new object was created in the process.
So, any modifications on your string object, you would
really be creating those many new objects of class String.
TALENTSPRINT | © Copyright 2012
6
String Handling
The following diagram illustrates the immutability concept:
String x = “Java”;
TALENTSPRINT | © Copyright 2012
7
String Handling
The following diagram illustrates the immutability concept:
x = x + “Rules!”;
TALENTSPRINT | © Copyright 2012
8
String Handling
Difference between String Object and String Literal:
When we create a String using new operator,
everytime a new instance of String will be created.
Example: String str=new String(“TalentSprint”);
When we assign a string to a String reference a new
String object will be created only if that string is not
present in the String pool. Otherwise the reference
will point to the same old String object.
Example: String str=new String(“TalentSprint”);
TALENTSPRINT | © Copyright 2012
9
String Handling
Example:
1 public class TestString{
2 public static void main(String[] args){
3
String a = "Java";//line 1
4
String b = new String(a);//line 2
5
String c = "Java";//line 3
6
System.out.print((a == b)+",");
7
System.out.print((a == c));
8 }
9}
Output is: false,true
TALENTSPRINT | © Copyright 2012
10
String Handling
Important methods of String class:
charAt()
Syntax: public char charAt(int index)
This method returns the character at the specified index.
startsWith()
Syntax: public boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
endsWith()
Syntax: public boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
TALENTSPRINT | © Copyright 2012
11
String Handling
Important methods of String class:
substring()
Syntax: public String substring(int beginIndex)
Returns a new string that is a substring of this string. The
substring begins with the character at specified index and
extends to the end of this string.
concat()
Syntax: public String concat(String str)
Concatenates the specified string to the end of this string.
TALENTSPRINT | © Copyright 2012
12
String Handling
Important methods of String class:
toLowerCase()
Syntax: public String toLowerCase()
Converts all of the characters in a String to lower case.
toUpperCase():
Syntax: public String toUpperCase()
Converts all of the characters in this String to upper case.
trim()
Syntax: public String trim()
Returns a copy of the string, with leading and trailing
whitespaces omitted.
TALENTSPRINT | © Copyright 2012
13
String Handling
Important methods of String class:
replace()
Syntax: public String replace(char oldChar,char newChar)
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
lastIndexOf()
Syntax: Public int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the
specified character.
lastIndexOf()
Syntax: Public int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence
of the specified substring.
TALENTSPRINT | © Copyright 2012
14
String Handling
Important methods of String class:
length()
Syntax: public int length()
Returns the length of this string.
hashCode()
Syntax: public int hashCode()
Returns a hash code for this string.
TALENTSPRINT | © Copyright 2012
15
String Handling
Important methods of String class:
compareTo(Object o)
Syntax: public int compareTo(Object o)
Compares this String to another Object.
compareToIgnoreCase(String str)
Syntax: public int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case
differences.
TALENTSPRINT | © Copyright 2012
16
String Handling
Difference between equals method and == operator:
There are two ways of comparison in Java. One is "=="
operator and another "equals()" method.
equals() - We use this method for comparing equality
of strings. This method compares the content of the
string object. Returns true if the string contents are
equal otherwise false.
Syntax: public boolean equals(Object anObject)
== operator: "==" compares the reference value of
string object. It returns true if the reference value is
same otherwise false.
TALENTSPRINT | © Copyright 2012
17
String Handling
StringBuffer
A StringBuffer is like a String, but it is mutable.
The length and content of the StringBuffer sequence can
be changed through certain method calls.
String is fixed length, in contrast, StringBuffer is growable
and writeable.
Characters in StringBuffer can be inserted, appended,
added, deleted anywhere and the size of the StringBuffer
will automatically grow or shrink to make room for this.
StringBuffer defines three constructors:
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)
TALENTSPRINT | © Copyright 2012
18
String Handling
Important methods in StringBuffer:
The important methods on a StringBuffer are the append
and insert methods, which are overloaded so as to accept
data of any type.
Below are three overloaded append methods:
1) StringBuffer append(String str)
2) StringBuffer append(int num)
3) StringBuffer append(int index, char ch)
The append method always adds the specified characters
at the end of the string if the index is not specified.
TALENTSPRINT | © Copyright 2012
19
String Handling
Important methods in StringBuffer:
Below is the syntax for insert method:
StringBuffer insert(int index, String str)
The insert method adds the characters at the specified
point. Here index specifies the point at which the string
will be inserted into the invoking StringBuffer object.
delete()- Removes all the characters of the StringBuffer
from the specified start to end position.
public StringBuffer delete(int start, int end)
TALENTSPRINT | © Copyright 2012
20
String Handling
StringTokenizer
StringTokenizer is a class used to break the
strings into tokens.
StringTokenizer is present in java.util package.
A token is a smaller piece of a string.
StringTokenizer breaks up a string into tokens
by specified delimeters.
The default delimeter is whitespace.
TALENTSPRINT | © Copyright 2012
21
String Handling
StringTokenizer
StringTokenizer is constructed like this:
StringTokenizer st=new StringTokenizer("we
are learning java with talentsprint");
While instantiating the StringTokenizer class you
can also pass your own delimiter as below.
StringTokenizer name = new
StringTokenizer(String str, delimiter);
Will create string tokens based on the delimiter
specified.
TALENTSPRINT | © Copyright 2012
22
String Handling
StringTokenizer
The following methods have been used in this program.
countTokens()
Gives the number of tokens remaining in the string.
hasMoreTokens()
It gives true if more tokens are available, else false.
nextToken():
It gives the next token available in the string.
TALENTSPRINT | © Copyright 2012
23
String Handling
StringTokenizer
1 import java.util.*;
2 public class StringTokenizing{
3
public static void main(String[] args){
4
StringTokenizer stringTokenizer = new
5
StringTokenizer("You are tokenizing a string");
6
System.out.println("The total no. of tokens
7
generated : " + stringTokenizer.countTokens());
8
while(stringTokenizer.hasMoreTokens()){
9
System.out.print(stringTokenizer.nextToken()+” “);
10
}
11
}
12 }
The following methods have been used in this program.
TALENTSPRINT | © Copyright 2012
24
String Handling
TALENTSPRINT | © Copyright 2012
25