0% found this document useful (0 votes)
47 views17 pages

String Theory

Chapter 15 discusses string handling in Java, detailing how to create and manipulate strings using the String class. It covers methods for creating strings implicitly and explicitly, as well as various string manipulation methods such as toLowerCase, toUpperCase, length, charAt, indexOf, lastIndexOf, concat, equals, and compareTo. The chapter emphasizes the importance of understanding string comparison and memory allocation in Java.

Uploaded by

hitlerfather1889
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
47 views17 pages

String Theory

Chapter 15 discusses string handling in Java, detailing how to create and manipulate strings using the String class. It covers methods for creating strings implicitly and explicitly, as well as various string manipulation methods such as toLowerCase, toUpperCase, length, charAt, indexOf, lastIndexOf, concat, equals, and compareTo. The chapter emphasizes the importance of understanding string comparison and memory allocation in Java.

Uploaded by

hitlerfather1889
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Chanter 15 String Handling haracters enclosed within double quotes, Astring isa data type used to set of dl represent text. tiscomprsed of 9 set fan in cbects and prov ae a of platform provides the String class to create and process strings. Java U features that ease the process of string handling, BE] 15.1 Croating strings Strings in Java are represented as objects of the String class, created by declaring objects of string type class and intialising th objects by using: which i defined in the Java.1ang package There va with string constants. In J8V@, YOU can create Ry + The String literal (Implicitly) + The new keyword (Explicitly) 15.1.1 Creating Strings Implicitly them in d Using this technique, the strings are formed by writing a series of characters ane Fs em ong 5, the Java compiler impli creates an objet ofthe String cas 2 _ quotes. Syntax: st tring"; String objectNane = "Series of characters that make feed t ne For example, you can write a statement as: String myCoffee = "Espresso"; Each string is stored in the computer memory as a sequence in the string. dex of 2 and so on. This tyt of characters as shown in Figure 15.1. Each character ing i . its position wit “The frst character has an index of O, the second characte string has an index which denotes its position withit ee ate t has an index of 1, and the third character has an in pe of indexing is called zero-based indexing because the string indexes start at zero. myColfee ——> Be al “The variable name refers [tothe whole string. | Figure 15.1: String - Memory Allocation 15.1.2 Creating Strings Explicitly This technique uses the new keyword to create a string object. The objects of the String class are created inthe same manner as you create objects of other classes. There is also a constructor in the String class that accepts a string as @ parameter and creates a unique string, It has the syntax: String objectName = new String(); For example, you can rewrite the earlier statement with the explicit use of the new operator as: String myCoffee = new String ("Espresso"); named nycoffee, storing the address whore the vq le lue riabl "Espn, 5. 550", te zu: in igure Oi stored ig " ror Computer myCoffee [iy jable name Address where the ——} | object is stored in memory Figure 15.2: Creating a String instance apie mycoffee contains the address where the obj pote or indicate that the content is an address and not th re epee pe offers a number of methods to support a ran oerring, comparing and searching strings, extracting lect is stored in Memory fe Value itself, "Y-AN arrow has been aad in ing Pa jna strin id -es present in between the string. the spac erove seringobject -trim() je Trimbeno. java */ public class TrimDemo public static void main(String args[]) ence { | Traling spaces | remove String testString = " String with leading and trailing spaces. [Link].print1n("Trinmed string is:"); system. [Link]([Link]()); {Leading ‘spaces removed.| | Spaces in between the string aa are retained. 7 that you can access member methods of a class using the syntax objectName,MethodName( ). AsString isa clas its method 'in() has been accessed in the same ‘way using the object name, ie., [Link](). Bill 153 toLowercase() Method The ! tolowerCase() method converts each character in a string to lowercase. However ifthe string contains any spec! "itremains unchanged, tins | (403) O_ <= §$ $= ‘Syntax: stringddject. toLowercase() /* ToLowerCaseDeno. java */ public class ToLowerCaseDemo { public static void main(String args[]) { String testString = "Testing The toLowerCase() Method."; System. out. print1n(testString. toLowerCase()); ee }, } Hl] 15.4 toUpperCase() Method The toUpperCase() method converts each character ina string to uppercase, However if the string contains a MY Specia} character, it remains unchanged. ‘Syntax: [Link]() Mises 3 * ToUpperCaseDemo. java */ public class ToUpperCaseDeno NF BI { TESTING THE TOUPPERCASE() Mi 4 public static void main(String args[]) ) eet 6 String testString = "Testing The toUpperCase() Method."; ‘Special characters i | remain unafeted fi [Link]([Link]()); yer } | 15.5 tength() Method The Length() method returns the length ofa string, The length is equal to the number of characters present nthe string including the white spaces, Syntax: [Link]() (404) | kins Computer Applications x java * Lengthdemo pemo hoe ong es clas gtatic void main(String args[]) ic ‘1 " Le { cering teststring = ‘Arkenstone" ; NAH Of Arkenstone ig 10 [Link]( "Length of " + teststring 4 » j, «---———. = teststring. length()); : « chart) Method method accepts an index number as its argument and retur A ni fhe string ranges from O to length() ~1, the character present at that particular rt re index | oo at (index ot agooject-char ¢ ) 2 and this method using the following example, where the test [Link](S) will return character "Sat index 5, pend O1234 56 789 testString —+>] aR] xk] e|n |! ‘tring stores a value "ARKENSTONE" ysundet The [Link](5) The method returns character at position r [Link] */ public class CharAtDeno public static void main(String args[]) The character at Sth position is S é : string testString = "ARKENSTONE"; Fi [Link].print1n("The character at Sth position is " } + [Link](5)); ‘the indexOF() method returns the index (position) of the first occurrence of the specified character in a string. The character is specified as an argument to this method. If the character is present in the string, the method will return the index number; otherwise, it will return -1. - Bl}15.7 indexor() Method - Syntax: stringObject. indexof (char) ‘Song Handling Kips | (405 where the test String stores a value "ARKENSToNe» understand this method using the following example, a . Let us nd this using 8 the first occurrence of character "E Inthe teststring. method call testString. indexOF(*E') will return 3, ie, oa eau ‘ethod returns the index of the arse Coc ot cnarslet ed [Link]) ‘Second occurrence character 'E! GOO. 0 sft oly |e] testString ——>| = z Dene J* [Link] */ public class IndexofDemo Ca { [Link]('€}) is ¢ rae static void main(String args[]) [Link]('G') is -4 String testString = "ARKENSTONE"; System. [Link]("[Link](’E') is " + [Link]('e") System. out. printIn("testString. indexof('G') is " + [Link]('g')); - a 10} BEI] 15.8 tastindexof() Method The lastIndexOF() method returns the index (position) of the /ast occurrence of the specified character ina string. This means that if a character occurs more than once in the string, the lastIndexOF() method returns the index value of its last occurrence. If the character does not occur in the string, it returns -1. Syntax: stringObject. lastIndexOf (char) Letus understand this method using the following example, where the testString stores value "ARKENSTONE". The method call test String. 1astIndex0#("E") willretur 9, ie, the last occurrence of character "E' in the testString. testString ——>] A] R a ° z a /* LastIndexOfDemo, java */ 2 public class LastIndexOfDemo 3 { : ae static void main(String args[]) testString JastindexOt('E’) is 9 2 testString lastindexO1(') is -1 String testString = "ARKENSTONE"; (406 } | kins ‘Computer Applications X [Link](“teststring, lastinde: + [Link]('e")); [Link]("testString. lastindexor: + [Link]('G')); XOF("E') is ("6") is 59 coneat() Method (aod js or concatenate two tings, on ngs. concat(string?) ollowing | example, where string! stores a value "SAVE" and string? stores a value "WATER", The value by stringl- concat(string2) will be "SAVE WATER", (One Naz En 0 1 2314 stringl—>| $ | A] V] E stringz—>]w] A] T|E|R \ tring].concat(string2) stringg—>]S}A]v]E| |w] a j* concatDeno. java */ public class ConcatDeno public static void main(String args[]) { , string stringl = "SAVE "; Concatenated string is SAVE WATER String string2 = "WATER" String string3 = [Link](string2); [Link]("Concatenated string is " + string3); Ntethat you can also use the + operator to join two strings. For example, the following statements in the above program Wilabo produce the same result. String string4 = string + string2; ‘[Link].print1n("Concatenated string is " + string4); Hansog is | (407) BBY) 15.10 equats() Method The equal s() method compares two strings to check whether they are equal or not. The resul “they are equal, otherwise the result is False. For this method, the corresponding uppercase are different. That means, 'G' and ‘g' are not equal Syntax: 5. boolean valve try and lowercase character [Link](string2) 1 [Link] */ ae 2 public class EqualsDemo 3 { 4 Public static void main(String args[]) s { 6 String string = "Computer" Both strings are equal 7 String string2 = “Computer; 8 8 if (string1 equals(string2)) 1e [Link]("goth strings are equal"); u else 2 System. out. printin("soth strings NOT are equal"); 23 } 4 } \etus grasp the concept by understanding the difference between String word1, word2; if (Word1 == word2) .. and if ([Link](word2)) a The equality test (==) is true if the contents of variables contents are the values themselves, However, for a referer stored, Thus, for a reference data type, equals() method is true if the String wordi and word2 are the same. Fora primitive datatype, the ince data type, the contents are addresses where the strings are the equality testis true if both variables refer to the same address. The result of objects these two variables refer to contain the same string value, Figure 15.3 is the schematic representation of scenario where Word and word? refer to the same object. Therefore, the addresses stored in word] and word2 are same. inthis case: word1 == word2 will evaluate to true [Link](word2) will evaluate to true Word! == word ist word .equals(word2) is thie Figure 15.3: Referring to the Same Object the schematic representation of scenario where word1 and word2 refer to diffe ferent ss 5% efor, the addresses stored word and word2 are diferent. in obits with the same this case: +jav e 53 cee will evaluate to false jals(word2) will evaluate to true or 0 word] word2 Addresses stored in word’ and word? are different, ‘; word! == word2 is false ‘Java’ ‘Java’ [Link](word2) is true Figure 15.4: Referring to Different Objects with the Same Value equalsignoreCase() Method ry sit walsien we percase O el ettod, 50 ng) equalstgnore oreCase() method compares two strings to check whether they are equal or not after ignoring their lowercase). The result isa boolean value true if they are equal, otherwise the result is False. For this perateresponding uppercase ad lowercase characters ae the same, That means ('and'g' are equal. Case(string2) ualsTgnoreDemo. java */ /* 9) public class EqualsIgnoreDemo public static void main(String args{]) { String string1 = "computer"; o ui String string2 = "CoMPuter"; Both strings are equal if ([Link](string2)) [Link]("Both strings are equal"); else [Link]("Both strings NOT are equal"); } . —_— 4s the equality ofthe strings But ko cheeg BEI) 15.12 compareto() Method d compares two strings. Itnot only chee! smaller than the other string. The compareTo() metho string is bigger oF syntax: [Link](string2) parison of strings is based on the Unicode value sographically* The com| ‘of each character present in the strings. The character represented by str'ing1 is compared lexic to the character sequence represented by stringy a. ‘ following logic: in + Gf string > string2 theres » if stringl < string2 the result string? the result will beO, Le. result =0 differ in the frst character, for example, "CAT" ang » ple, CAT nda, ult wll be a positive integer, i., result > 0 will be a negative integer, Le., result string2—> ‘Comparison 1: string].compareTo(string2) —[ez70= 33] Comparison siring2,compareTo(string!) —>| 70-67 =3 Comparison 3: —»[ers7=0] [65-65=0 ] [p484=0 string] compareTo(string]) Figure 15.5: Two Strings Differ in the First Character performed, the result is the difference of the equivalent ASCII codes of the When the lexicographical comparison is corresponding characters where they differ in the first occurrence. The following steps explain the logic behind the comparisons shown in Figure 15.5. ++ Comparison 1: When you compare "CAT" with "FOX", the first occurrence where these two strings differ is 'C* and 'F', The results -3 (= 67-70) which is the difference of their equivalent ASCII codes. + Comparison 2: When you compare "FOX" with "CAT", the first occurrence where these two strings differ is a and 'C’. The result is 3 (= 70-67) which is the difference of their equivalent ASCII codes. + Comparison 3: While comparing "CAT" with "CAT", there is no difference because th ye ASCII codes of the corresponding characters are same. Thus, the result is 0. cleiters precede all the lowercase letters. That means, uppet Lexicographie orders sa jictionary order, except that all the upperea cease A’ comes before lowercase Computer Applications X Ce main(String args[]) = “CAT'S = "FOX" | ut .println([Link](string2)); | ut.print1n([Link](string1)) ; — [Link](stringl. compareTo(string1)); gystem-O system-0 system-0 —-. fer an example where two strings have the same first character but a different second character. For id on rand COT" as shown in Figure 15.6. ae r= —— Equivalent ASCII Code string. —> fai] T 7 iro 84 4———__Equivatent ascit Code | string2—> 0%) T Comparison 1: Ss [Link](string2) ——> | 67-67 = 0 | [65-79 = -14) Comparison 2: [Link](string!) ——>[ 67-67 = 0 | [79-65 = 14 Comparison 3: 7 [Link](string2) ——»| 67-67 = 0 | | 79-79= 0 | | 84-84 =0 Figure 15.6: Two Strings Differ in the Second Character ne following steps explain the logic behind the comparisons shown in Figure 15.6. + Comparison 1: When you compare "CAT" with "COT", the first occurrence where these two strings differ is "A" and '0". The result is -14 (= 65-79) which is the difference of their equivalent ASCII codes. + Comparison 2: When you compare "COT" with "CAT", the first occurrence where these two strings differ is 'O" and ‘A’. The result is 14 (= 79-65) which is the difference of their equivalent ASCII codes. + Comparison 3: While comparing "COT" with "COT", there is no difference because the ASCII codes of the corresponding characters are same. Thus, the result is 0. Pe Handing, Kips | (411) /* CompareTodeno2. java */ public class CompareToDeno2 { public static void main(String args[]) itd { String stringl = "car"; String string2 = "cor"; [Link]. printn([Link](string2)); 10 [Link]. print1n(string2. compareTo(string1)); 2 System. out. printn([Link](stringl)); 3} Bill 15.13 compareTolgnore() Method The compareToIgnore() method compares two strings lexicographically, ignoring case diferences in the strings, Syntax: [Link](string2) 'enoring case differences, the character sequence represented by string! is compared lexicographically to the character Sequence represented by string? as per the following logic: + if string > string? the result willbe a positive integer, e., result > 0 + if string < string2 the result will be anegative integer, ie, result = € = string] substring(5) Figure 15.7: Substring of a String pa /* SubstringDemo. java */ public class SubstringDemo B “4 public static void main(String args[]) Caos } 6 String stringl = "BLUE MOON"; 7 8 [Link]([Link](5))3 3 } we) Sting Handling ips | (413) ——_— F string of the given stri However, the ‘abe Fant ofthe Substring) method that returns a new string ee ae dex dT Ade ag i ey syntax NS at the specitied start Index and extends to the chara Stringog. ae SS substring ing startIndex, int endindex) wil es Parle where stringt store avlue “RISE AND SHINE". Seay atte ee AND" witha StartIndex of 5 that extends to endIndex--1, i.e, 7 (= (S, 8) startindex. endindex 12:13 OMI 23nd) 5/16 671, 8910 IL E = N so — Tati [5] Js]u]i string] substring(5,8) Figure 45.8: Substring with a Start and End Indox f* Substrg, NgDemo2, Public cy 2. java */ { S Substringdeno2 Cg ms Static voig main(String args[]) String string = “RISE AND SHINE"; [Link]. printin([Link](s, 8))3 Bill 15.16 startsWith() Method The startswith() meth string starts with the speci Syntax: 1od checks whether a string starts with a particular string. The method returns true if the given fied prefix, otherwise it retums False. stringobject. startshith(prefixstr) CURE 2 /* StartswithDeno. java */ 2 public class startswithDeno aa ( Cong Public static void main(String args[]) 4 5 { 6 String stringl = “swachh Bharat"; 7 String string2 = "swachh"; ‘Computer Applications X ysten-out println([Link](string2)), enc metiod checks whether a string ends with apart tng, The method retums si ie specified sux, otherwise it returns False, ends ‘true if the given - aatane/, swithDemo. java oe Ent ithD ic class EndsWithDemo public c public static void main(String args[]) Pg string stringi = "Swachh Bharat"; String string2 = “Bharat”; system. out. printin([Link](string2)); py 1548 valueOf() Method evalueo#() method returns the string representation of the argument. stax: string. valueOf (data) ‘Tere are a number of variants of this method as shown below: 1. public static String valueOf (boolean b) 1 public static String valueOf(char c) 3, public static String valueOf(int i) 4, public static String valueOf(long 1) 5. public static String valueOf(float f) 6. public static String valueOf(double d) 1. public static String valueOf(char[] data) § public static String valueOf(char[] data, int offset, int count) freample, when invoked with character 'Z' the valueO#() method returns a string value "2". When invoked with imeger value 1234, the valueOf() method returns a string value "1234". ng Handing ios | (418) For variant 8, the of fset argument is the index of the first character of the subarray. The count argument Species the length of the subarray. For example, if the char array is defined as. char[] myChararray = {'S', 'U', 'N', 'D', ‘AT, 'Y"}s The subarray with of fset = 3 and count = 3 will be 'Y' as shown in Figure 15.9, myCharArray —> € string] valueOf(myCharArray, 3, 3) Figure 45.9: Method valueOM{ ) with offset and count eer R ERT a /* [Link] */ /2 public class Valueofdeno 3 { ea public static void main(String args[]) { 6 boolean myBoolean = true; 7 char myChar = 'z'; 8 int myInt = 1234; 9 long myLong = 987654321; 16 float myFloat = 343.55; a double myDouble = 34333.566665; 12 char[] myChararray = {*S', "U', 'N', 'D', ‘At, ‘v3 13 14 //String representation of the boolean argunent. 15 System. out. print1n (String. valueOf(myBoolean)); 16 v7 //String representation of the char argument. 18 System. out. print1n([Link](myChar)); 19 20 //String representation of the int argument. ener 2 [Link]. print1n(String. valueOf(myInt)); - 22 a 23 //String representation of the long argument. ie 24 Systen. out. printn(String. valueof (nyLong)); cay 25 343.55 26 //String representation of the float argunent. 34393,566665, 27 System. out. print1n(String. valueOf(myFloat)) ; SUNDAY 28 DAY 29 /JString representation of the double argument. 38 [Link] .print1n(String. valueOf(myDouble) ); (416) | kios Computer Applications X — ppstrine representation of the char array argument [Link]-printin([Link](nychararray)); p/string representation of the char array argument from an offset [Link] .printIn([Link](myChararray, 3, 3); ’ 439 stingray Jearnt in the previous sections that you can define and initialise a string using the String class. You can access you of the string using the charAt () method as shown in Figure 15.10. In this illustration, a String named colour am vee defined with 2 value "RED". The chartAt(1) method will give you the value 'E' at index1. 13 ommie2 colour ——> [Link](1) Figure 15.10: A String 45.20 shows its code implementation. prora™ yr stringdeno. java */ public class StringDeno public static void main(String args[]) { [Link](1): & string colour = "RED"; [Link].print1n("[Link](1): " + colour. charAt(1))3 Similar to defining a String, you can also define an array of strings called a String Array that can store multiple strings as shown in Figure 15.11. In this illustration: + AString Array named colours has been defined with values "RED", "BLUE", and "GREEN". + Individual elements of the String Array can be accessed using the row index. For example, colours [2] will give you the value "GREEN" at row index2. + You can access individual characters of element colours[2] using the chartAt() method. For example, colours[2].chartAt (4) method will give you the value 'N' at column index4. pesiae Column Index colours Sj OU etesored rlelo ¢—coloursfo) §} Lo Ed falilula] |—cotoursup é x GI]R/EJE 4—coloursi2)) colours[2].charAt(4) Figure 15.11: String Array Program 15.21 shows its code implementation. eRe /* [Link] */ public class StringArray public static void main(String args[]) lad { colours{0]: RED String colours[] = {"RED", "BLUE", "GREEN"}; colours[1]: BLUE colours[2]: GREEN [Link]("colours[@]: " + colours[@]); colours[0].charAt(1): 2 [Link].print1n("colours[1]: " + colours[1]); colours[1].charAt(2): U 18 [Link].print1n("colours[2]: " + colours[2]); colours[2].charAt(4): N, nn 12 [Link]("colours[@].charAt(1): " + colours[@].charAt(1)); B [Link]("colours[1].charAt(2): " + colours[1].charAt(2)); 4 System. out .print1n("colours[2].charAt(4): " + colours[2].charAt(4)); Bo } a6 } Solved Programming Exercises ee UL eee Write a program to input a word and display each character of the word on a separate line. Sample input: ICSE Sample Output: I c “a

You might also like