20
Java Programming Strings Lecture10

Lecture 10 Strings

Embed Size (px)

DESCRIPTION

Lecture 10 java Strings

Citation preview

Page 1: Lecture 10 Strings

Java Programming

Strings

Lecture‐10

Page 2: Lecture 10 Strings

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 manipulatingString class provides many operations for manipulating strings.

• Constructors

• Utility

• Comparisons

C i• Conversions• An object of the String class represents a string of characters.

Page 3: Lecture 10 Strings

String Basics‐Declaration and CreationDo 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”);

Page 4: Lecture 10 Strings

Initializing StringsInitializing StringsString variable declaration

− If we declare a String variable without initializationIf we declare a String variable without initialization

− e.g String myString; what would happen?

Have to initialize String variable with special null value, ifHave to initialize String variable with special null value, if you really don’t want to initialize it with useful value at the start.

ll− String myString = null;

Page 5: Lecture 10 Strings

String ConstructorsString ConstructorsEmpty String

String str = new String( );String str = new String( );

str 0

With message

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

ObjectReference

strJava Strings

Note! String str = “Java Strings”; produces the same result

Page 6: Lecture 10 Strings

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 hreference without the others being aware of the change.

Page 7: Lecture 10 Strings

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

OKLess efficient:

t

Java

word2

OK wastes memory

Page 8: Lecture 10 Strings

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

Page 9: Lecture 10 Strings

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

Page 10: Lecture 10 Strings

String operationsString operations

Page 11: Lecture 10 Strings

• 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

Page 12: Lecture 10 Strings

Concatenation Exammple

D l d t t t t i th t t t 2 t th d f t 1Declare 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 discontentstr2

This is the winterstr1

This is the winter of our discontent

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

Page 13: Lecture 10 Strings

Other Useful methods of String ClassgtoCharArray( );

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

Page 14: Lecture 10 Strings

String Comparisonh ll− Shallow comparison = =

− Deep comparison equals( );

− Deep comparison compareTo( );

The == will check whether the two String variables refer to h ithe same string

− If they reference separate strings, you will get false regardless of whether or not the strings happen to be identicalof 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.

str1A string

str2

g

Page 15: Lecture 10 Strings

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 correspondingcharacter 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 htwo strings ignoring the case of the string characters.

Page 16: Lecture 10 Strings

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

Page 17: Lecture 10 Strings

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

Page 18: Lecture 10 Strings

StringBuffer ClassStringBuffer objects can be altered directly

A String object is always a fixed stringg j y g

How to create StringBuffer objects?

− StringBuffer string1 = “Hello How are you”;//not allowedString 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 ywhich may or may not contain a string and if it does, the string need not occupy all of the buffer

Page 19: Lecture 10 Strings

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 intstring1.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

Page 20: Lecture 10 Strings

Other Useful methods of StringBuffer ClassgYou can produce a String object from a StringBuffer object by using the toString( ) method of the StringBuffer classg g g

− String string2 = string1.toString( );

How does the compiler handles the string concatenation of String objects?

Append( ) and toString( ) methods are usedAppend( ) and toString( ) methods are used−String message = “hello” + “How are you”;

−String message = new StringBuffer( ) .append(“Hello”).append(“how are you”).toString( );