You are on page 1of 20

Java Programming

Strings
Lecture10
Strings
A t i i f b l A string is a sequence of symbols.
Java provides you with String class
java.lang package, which does not require an import
statement.
String class provides many operations for manipulating String class provides many operations for manipulating
strings.
Constructors
Utility
Comparisons
C i Conversions
An object of the String class represents a string of characters.
String BasicsDeclaration and Creation
Do not need new to create String
String str = niit"; g
str=seecs;
String name=str; g ;
String stringName= new String (string value);
String city= new String (Islamabad);
Initializing Strings Initializing Strings
String variable declaration
If we declare a String variable without initialization If we declare a String variable without initialization
e.g String myString; what would happen?
Have to initialize String variable with special null value, if Have to initialize String variable with special null value, if
you really dont want to initialize it with useful value at the
start.
ll String myString = null;
String Constructors String Constructors
Empty String
String str = new String( ); String str = new String( );
str
0
With message
String str = new String(Java Strings);
Object
Reference
str
Java Strings
Note! String str = Java Strings; produces the same result
Immutability
Characters in Strings can not be changed after the
Strings are created
Once created, a string cannot be changed: none of its
methods changes the string.
Such objects are called immutable.
Immutable objects are convenient because several
references can point to the same object safely: there is
no danger of changing an object through one
f i h h h b i f h reference without the others being aware of the
change.
Advantages Of Immutability
Uses less memory.
String word1 = "Java";
String word1 = Java";
String word1 = Java ;
String word2 = word1;
String word1 Java ;
String word2 = new String(word1);
word1
Java"
Java"
Java"
word1
word2
OK
Less efficient:
t
Java
word2
OK wastes memory
String Objects
S i bj i bl h b h d h String objects are immutable -- they cannot be changed once they
have been created. References to string objects may be changed.
String str1 = new String (I like dogs.);
String str2 = new String(I prefer cats.);
str1 = str2; //reassign reference
str1
I like dogs.
str2
I prefer cats.
Automatic garbage collection will reclaim unreferenced objects
String Operations in Java
Following are some useful classes that Following are some useful classes that
Java provides for String operations.
String Class
StringBuffer Class
StringTokenizer Class
9
String operations String operations
int length()
char charAt(int index)
indexOf( ) & lastIndexOf( )
indexOf(char ch) // first position of 'ch'
indexOf(String str) // first position of 'str'
lastIndexOf(char ch) // last position of 'ch'
lastIndexOf(String str) // last position of 'str' ( g ) p
startsWith(String prefix) & endsWith(String suffix )
String Substring (int) & String Substring (int startindex, int lastindex)
public String toLowerCase() & public String toUpperCase()
public String trim() - Returns a copy of the string, with leading and trailing whitespace omitted.
public String replace(char oldChar, char newChar) - Returns a new string resulting from replacing
all occurrences of oldChar in this string with newChar.
i ( ) i Concatenation (+) returns a string
Concatenation Exammple
D l d t t t t i th t t t 2 t th d f t 1 Declare and construct two strings, then concatenate str2 to the end of str1
String str1 = new String(This is the winter );
String str2 = new String(of our discontent);
str1 = str1.concat(str2); //message to str1 to concat str2 to its end
of our discontent
str2
This is the winter
str1
This is the winter of our discontent
Note! The same result occurs for str1 = str1 + str2;
Other Useful methods of String Class g
toCharArray( );
String string1 = Hello How are you; String string1 Hello How are you ;
char [ ] array=string1.toCharArray( );
copyValueOf( ); copyValueOf( );
Static method
String string2; g g ;
string2=String.copyValueOf(array);//copyValueOf(array,6,3);
String Comparison
h ll Shallow comparison = =
Deep comparison equals( );
Deep comparison compareTo( );
The == will check whether the two String variables refer to
h i the same string
If they reference separate strings, you will get false regardless
of whether or not the strings happen to be identical of whether or not the strings happen to be identical
It does not compare the strings themselves, it compares the
references to the strings, hence called shallow comparison.
str1
A string
str2
g
String Comparison
Deep Comparison
Using equals( ) method of the String class ; Using equals( ) method of the String class.;
Equals( ) is used to decide whether the strings referred by two
String variables are equal or not.
This method does a case sensitive comparison
Two strings are equal if they are the same length and each
character in one string is identical to the corresponding character in one string is identical to the corresponding
character in the other.
Use equalsIgnoreCase( ) method to check for equality between
i i i h f h i h two strings ignoring the case of the string characters.
Same Object / Same Reference
String s1 = new String (I am a string);
String s2 = a string;
String s3 = s1.substring(0,4);
S i i String s4 = a string;
String s5 = s3 + s2;
if (s5 == s1) { }
if (s1.equals(s5)) { }
true
false
if (s2 == s4) { }
if (s5.equals(s3+s4)) { }
true
false
String Comparison String Comparison
Deep Comparison
Using compareTo( ) method of the String class
compareTo( ) is used to decide whether the string object from
which it is called is less than , equal to or greater than the string
passed as argument to it.
Returns an integer which is negative if the String object is less than Returns an integer which is negative if the String object is less than
the argument String
Returns positive integer if the String object is greater than the
argument String.
Returns zero if both are equal.
System out println(hello compareTo(hell)); // 1 System.out.println( hello .compareTo( hell )); // 1
StringBuffer Class
StringBuffer objects can be altered directly
A String object is always a fixed string g j y g
How to create StringBuffer objects?
StringBuffer string1 = Hello How are you;//not allowed String uffer string Hello How are you ;//not allowed
StringBuffer string1 = new StringBuffer(Hello How are you);
StringBuffer contains a block of memory called buffer g y
which may or may not contain a string and if it does, the
string need not occupy all of the buffer
Other Useful methods of StringBuffer Class
append( );
string1.append(To); string1.append( To );
string1.append(string2,3,3); //appending substrings
string1 append(x);//where x is an int string1.append(x);//where x is an int
insert( );
string1 insert(4 how);//4 is the index position string1.insert(4, how );//4 is the index position
insert also has many versions like append
Other Useful methods of StringBuffer Class g
You can produce a String object from a StringBuffer object by
using the toString( ) method of the StringBuffer class g g g
String string2 = string1.toString( );
How does the compiler handles the string concatenation of
String objects?
Append( ) and toString( ) methods are used Append( ) and toString( ) methods are used
String message = hello + How are you;
String message = new StringBuffer( )
.append(Hello).append(how are you).toString( );

You might also like