You are on page 1of 10
CHAPTER STRINGS ost of the data that transmits on Internet will be in the form of groups of characters. Such ps of characters are called ‘strings’. For example, in a business order form, a person enters details like his name, credit card number, address, etc., which are all nothing but ly. So a string represents a group of characters. ++ languages, a string represents an array of characters, where the last character will be ‘\O" ull character). This last character being ‘\0” represents the end of the string. But this is not aid in Java. In Java, a string is an object of String class. It is not a character array. Im Java, we +: character arrays also, but strings are given a different treatment because of their extensive use crnet. JavaSoft people have created a class separately with the name ‘String’ in java.lang age) package with all necessary methods to work with strings. though, String is a class, it is used often in the form of a data type, as: string 5 = "Java"; LL LLL ELAS is a variable of the data type String’ Liu) Quest Is String a class or data type? String isa class in java.lang package. But in Java, all classes are also considered as data types. So we can take String as a data type also. Can we call a class as a data type? Yes, a class is also called ‘user-defined’ data type. This is because a user can create a class. Creating Strings There are three ways to create strings in Java: assigning a group of characters to a string type variable: ree Q We can create a string just by ring si //declare string type variable F String si //declare Sitifgn a group of characters to 1t 4 Preceding two statements can be combined and written as: Scanned with CamScanner wt 98 | Chapter 9 string s = "Hello"; Hello” in that object. JVM creates an object and stores the string: bal ns od rciernced by the variable ‘6. Remember, creating object means allottin on 2) Weean eveate an object to String class by allocating memory using new operato ke creating an object to any class, like given here string s = new string@ Hen . Then, we © doing two things. First, we are creating object using new operator. string: “Hello” into the object Fb The third way of creating the strings is by converting the character arrays into ake @ character type array: arr] | with some characters, as: char arr{ J = ('e"y 2 Now create a string object, by passing the array name to it, as: saa AR string s = new String(arr); aan Now the String object ‘s’ contains the string: “chairs”. This means all the characters of the: copied into the string. If we do not want all the characters of the array into the string, also mention which characters we need, as: String s = new string(arr, 2.3 Here, starting from 2v¢ character a total of 3 characters are copied into the string s. Sharacters are c-h-ai-r-s. Since counting starts from 0, the 0 character in the, array 2% (Character is ‘a’. Starting from ‘a’, a total of three characters implies ‘air’, So characters are copied into the string s. String Class Methods lt us have a look at which methods are available in String clase and how they can be us String concat(String 5) Herp, ‘concat’ is the method name. Since .s S to String” slimes oe te oma), ae POE Stag! ae canbe cal the parenthesis after the method name. It the concai{) method while it is c. ‘String’ before the method name. 11 So the preceding method c is, $1.cone: . ‘his indicates that the met} aie! nore ‘an be used as: String '$3''='61; concat(s2); gg Now concat() method concat Ir z returns a third st ncatenates or joins tring 6 fesult. So, ifs1=*Hyderat and soeripoits O strings (1 and 2) ana a : tig, nt 82" bad, then welcarreynet wi be “Hyderaba The same concate ie aoe Bie san “tenation can be done by “sing “+” operator which is cal For example, we can ase Scanned with CamScanner sub string is found turfs 2. If the sul returns a new string cc the string. For ex end of sl. ving substring( characters starting s1.substring(5,10) retur String toLowerCa: returns that lower- Scanned with CamScanner 6 all characters into upper case, and QString tovppercase (): This method convert upper-cased string string trim(): This method removes spaces from the beginning and ending of a tring is written as" Ravi Kiran *, the spaces before “Ravi” and after “Kiran” are an and should be removed. This is achieved by trim). Note that this method does not spaces in the middle of the string, For example, the space between “Ravi” and “Kiran removed = nt int 42) char arr| int 13): This method copies from a string into a character array, The characters starting from position it to 2% string are copied into the array ‘arr’ to a location starting from 13. Counting of charaetes string will start from 0" position a (delimiter); This method is useful to break a string into pieces at presented by the delimiter, The resultant pieces are returned into a String type uppose, the delimiter is a comma, then the string is cut into pieces wherever g comma | found. Let us have a look on program which will help us to understand strings. © a program which will help us to understand how to create styigs and how: Program 1: Writ important methods of String class. /soemo of String class methods class stroemo public static void main(String args 1) //create strings in 3 ways String s1= "A book on Java"; String s2= new string('T like it"); Ghar arrfl= {'D',trtyte!,falytm!,"t separ ieet Ret ral string 53 new String(arr); i //display all the 3 strings ‘System. out.printIn(s1); : System.out print In(s2); system. out .printin(s3); a {find Vength of first string 2 System.out.printIn("Length of sl= "+ sl. lengthQ)); f //concatenate two strings System.out.printin("s1 and s2 joined= "+ si.concat(s2)); //concatenate three strings with + ‘ System.out.printIn(si+" from "+ 53); //test if string sl starts with a boolean x= sl.startswith("A™); if). System.out.printIn("s1 starts with \'a\! else System.out.printIn("s1 does not start with "A": //extract substring from s2, starting from O% © char String p = 52-substring(0.7); 2 char’ to ae /fextract substring from s3, starting from Om a Q String-q = 's3.substring(0,3); 7 7) vom Om Char to 8% chal A/concatenate the strin Systen-out-printin¢prays, a4 4 //convert s1 into uppercase nto y ang lowercase System. out. print inch ipper sl= "+s1. tol System.out.printIn("Lower si= pealwencase 0: 451, toLowerease (3; Scanned with CamScanner Let us write another prograt purpose, split() method is u Ss = str.sp Here, “delimiter” is a string th ‘to split the string. For exam comma splits it at a comma, pieces are stored into a oo Scanned with CamScanner 102 hapter 9 splitting a string class Strsplit public static void main(string args( J) t take a string str which is to be broken Serihg ere Me HHo, Ehis 15 &°b00K on Sava: (/declare a string type array s to store pieces String st Ii //split the string where a space is found in str S = str.split(” "); ‘display the pieces from s force Mao yeacten yeh; 14+) System.out.printin(s[iJ); \ jaxac strspliejava CAS Java strsplit Hello, this is 2 book on Sava String Comparison The relational operators like >, >=, <, other hand, methods like: compareTo() and e and != cannot be used to compare the strings. ‘quals() should be used in string comparison. Program 4: Let us write a program to compare two strings using {string comparison using == class Strcompare public static void main(string args 1) string sl= "Hello"; String s2= new String("Hello"); if (s1==s2) System.out.printIn("soth are same" ; else System.out.printinc"Not same"); Output he GAS davaclstreomare java as ENS fava cereooneay pe Scanned with CamScanner When an object number, Which. allotted to it Tt When JVM executes # reference number, 8 ‘larly when the f ng objects, not their Figure 9.1. Scanned with CamScanner 104 {Chapter 9 e difference between == operator compares the references of the string objects. It does not compare the objects equals!) method compares the contents. While comparing the strings, equals() ised as it yields the correct resuft ‘string comparison using == ss Strcompare public static void main(String args 1) string si= “Hello” String sd "Welle" if(S1ess2) ee system.out.printin("soth are same"); else: systemout-prantinc'sot sane" } C:\> javac strconpare.java 2\> java strcompare “ Both are same String sl = “Hello”; Here. JVM creates a String object and stores operator to create the string. We are u creating the String object, JVM uses and stores the object there Helo” in it. Observe that we are not using 'g assignment operator (=) for this Purpose. So, “Separate block of memory which is called string constant What is a string constant pool? manna constant pool is a separate block of memo ry Where the string obj Siang objec! is created direct, using assignmeny operator as: Strin, ee held by JVM. It string constant pool, % ello", then it is stored in When the next statement constant pool to kno the same object is So uent is already available paper tic lable thang (which is 81), then JVM Cee, not an Figure 9.2 oy Hence gj Hence, ‘Both are same”. Please ow whether the already avail another referenc ci Scanned with CamScanner In this case, pool, Ifit is @ String objects are Program 6: Write a p Scanned with CamScanner Scanned with CamScanner

You might also like