Java Programming Strings

Lecture‐10

Strings • A string t i iis a sequence off symbols. b l • Java provides you with String class • java.lang package, which does not require an import statement. • String class provides many operations for manipulating strings. • Constructors • Utility • Comparisons • Conversions C i • An object of the String class represents a string of characters.

String Basics‐Declaration and Creation Do not need new to create String

Stringg str = “niit"; str=“seecs”; Stringg name=str;; String stringName= new String (“string value”); String city= new String (“Islamabad”);

Initializing Strings ¾ String variable declaration − 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 you really don’t want to initialize it with useful value at the start. − String myString = null; ll

String Constructors Empty String

String str = new String( ); str

0

With message

String str = new String(“Java Strings’’); Reference str

Object 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 reference f without ih the h others h b being i aware off the h change.

Advantages Of Immutability Uses less memory. String word1 = "Java"; Java ; String word2 = word1;

word1

“Java"

String word1 = “Java"; Java ; String word2 = new String(word1); word1

“Java"

word2

“Java" Java

word2

OK

Less efficient: wastes t memory

String Objects String S i objects bj are iimmutable bl -- they h cannot b be changed h d once they h 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

str2

I like dogs.

I prefer cats.

Automatic garbage collection will reclaim unreferenced objects

String Operations in Java • Following are some useful classes that Java provides for String operations. – String Class – StringBuffer Class – StringTokenizer Class

9

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 ( g str)) // last p position of 'str' ƒ

• •

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.



Concatenation i (+) ( ) returns a string i

Concatenation Exammple D l Declare and d construct t t ttwo strings, t i th then concatenate t t str2 t 2 to t th the end d off str1 t 1 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 str2

str1

of our discontent

This is the winter This is the winter of our discontent

Note! The same result occurs for str1 = str1 + str2;

Other Useful methods of Stringg Class ¾ toCharArray( ); − String string1 = “Hello Hello How are you”; you ; char [ ] array=string1.toCharArray( );

¾ copyValueOf( ); − Static method g ; − Stringg string2; string2=String.copyValueOf(array);//copyValueOf(array,6,3);

String Comparison

− Shallow h ll comparison = = − Deep comparison

equals( );

− Deep comparison

compareTo( );

¾ The == will check whether the two String variables refer to the h same string i − If they reference separate strings, you will get false regardless 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 str2

A stringg

String Comparison ¾ Deep Comparison − Using equals( ) method of the String class 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 the other. ¾ Use equalsIgnoreCase( ) method to check for equality between two strings i ignoring i i the h case off the h string i characters. h

Same Object / Same Reference String s1 = new String (“I am a string”); String s2 = “ a string”; String s3 = s1.substring(0,4); S i s4 = “ a string”; String i ” String s5 = s3 + s2; if (s5 == s1) { } if (s1.equals(s5)) { }

false true

if (s2 == s4) { }

true

if (s5.equals(s3+s4)) { }

false

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 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( System out println(“hello” hello .compareTo( compareTo(“hell”)); hell )); // 1

StringBuffer Class ¾ StringBuffer objects can be altered directly ¾ A Stringg object j is always y a fixed stringg ¾ How to create StringBuffer objects? − String StringBuffer uffer string string1 = “Hello Hello How are you you”;//not ;//not allowed − StringBuffer string1 = new StringBuffer(“Hello How are you”);

¾ StringBuffer g contains a block of memoryy called buffer 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

¾ insert( ); − string1.insert(4, string1 insert(4 ” how how”);//4 );//4 is the index position − insert also has many versions like append

Other Useful methods of StringBuffer g Class ¾ You can produce a String object from a StringBuffer object by g ) method of the StringBuffer g class usingg the toString( − String string2 = string1.toString( );

¾ How does the compiler handles the string concatenation of String objects? ¾ Append( ) and toString( ) methods are used −String message = “hello” + “How are you”; −String message = new StringBuffer( ) .append(“Hello”).append(“how are you”).toString( );