You are on page 1of 10
Strings 1H. B. Prajopati 9 July "20, Core Java Technology String in Java 1 A string isa sequence of charac «In many programming languages, a string is considered as an array of. characters @ In Java, a string is considered as an abject of String class (ie java.lang.String) Creating a String Object ° 1 The Java compiler actually converts these string literals into String objects and passes to printin() method. 9 To create a string explicitly, we use the following syntax arlier, we have passed string literals to println() method i[Berine @ neu String (String in Javadi 18 Alternatively, we can declare and create a string using the following syntax: String # = "String in Java" 12 We can also create a string from an array of characters: char] chars [strings vat tatty tary” now’ String (chars): Table of contents @ String class © SuringButer cass © SerngTokenizer cass © Command Line Arguments Outline of Presentation String is Immutable 2 A String object is immutable. That means, its content changed. 1 For the following code, 2 new string object is created when the second statement is executed cannot be = ing @ = dave Sava EE String object String object plore CT tor save se” A, [for“teva se tringobjeet for “lava Ee” Stings ="i0va se; srw ee A a ae yy Interned String 18 As String is immutable, the JVM uses a unique instance for same string Iterals to save memory and improve efficiency. 1 Such instance is called interned | Program: String Comparison, Slide - 1[Eiass_StringComparisoat 2] “puviie atari void main (String(] arge){ 3 String s1 = "Java Si String 22 = “Java Si String s3 = new String("Java SE"); 8 System. out printin("String compariso: using == and at (si==82) 3 System, out .printin(s1+" +22); else 10 Syeten out. printin(s1+" +22); u if (sle=s3) YI Syevex. out. printia (e1+" 23) 4 else 1 Systez.out printia(si+" I= "+83); 16 System. out-printin("String comparison using equals() zethod") LL. + | Program: String Comparison, Slide - I] String Comparison «© For comparing values of two variables of primitive type we use == comparison operator. 19 But, since a string in Java is an object, two strings cannot be compared using == comparison operator. 18 To compare two strings, Java provides equals() method in String clas. 19 The signature of the equals() method is as follows: I SS as Program: String Comparison, Slide - II 44 (51. equate (s2)) | System-out-printin(sir” equals "+s2) 4 else 2g System.out-printin(si+" lequals "+s2) it(a1- equats(s3)) System-out.printin(si+" equals “4s3) alse 24 System.out.printin(si+” lequals "+83 Ordering and Comparison using compareTo() 1 To compare two string, we can also use compareTa() method, as shown below: [HcompareTe 2) «The compareTo() returns 0 if swe strings ate equal, Nate: equals) method returs boolean value The compareTo() can be used to order sting in lexicographic (Gictinary) order IF 31 comes ft (in escographic oder) than £2 then compara) wil return vale less than © a If st comes after 2 (in lesicoraphic ord), then compare T() wll secur vale greater than The enact return value wl be the dierence beeen the fst roneatehng characters of 31 and 2 yy Program: Comparison and Ordering, Slide - 1 Cina _StvingUonpareTat a] “public static void main(Str: String ei String 22 = (2 argsd¢ Java, Java ses String #3 = new String String 24 Java SE") peu String 5 int reeult<0; System. out. printin( ‘using conpareTo() ir (s1. compareTo (3) Systex. out .printia( else Syston. out .printia( tring comparicon chert +23) preston t= #483); System.out.print ("Ordering strings using compareTo(), AV=") it ((regult=s1. compareTo(s2)) <0){ | Program: Comparison and Ordering, Slide - III =z Other ways of String comparison 1 To compare two strings, we can use compareTo() © If we want to compare strings ignoring cases, we can use cqualsignoreCase() method. 12 To compare strings, we cannot use comparison operators such as a Program: Comparison and Ordering, Slide - II System. out n(result); @| System out prinzin("\t"+s1) System_out printin("\t"+82); ¥ eset 21 System.out. printin (result); 2 Systemout printin("\t' +82); 5 System.out printin("\t"+81) sys nt (“Ordering strings using spareTa(), RV=") 2 ie ((resultes2. compareto (24)) <0) < 2% System. out printin(result); 29| System-out princin("\r" +82) 3 System-out printin("\i"te4) : 3 ¥ eset x System.out.printin (result) 33| System-out printin("\t' tsa); 3a Systemout printin("\t"+82) A yy Program: Comparison and Ordering, Slide - IV String Methods eet chart Cort ne el Seb Tat lengths char eharAt (int index); ing coneat (String #2); ng substring(ine stare); ing substring (int start st int ena) Thee length(); method returns the rumber of characters 19 The charAt(index); method returns the character present on the specified index. The concat{s2); method returns a new string that concatenates invoking string with 52 ‘The substring(start); method returns a new string containing characters starting from start index to the last character. The substring(start. end); method returns a new string containing characters starting from start index to the end index ESN SS~S&« Program: Extract Information, Slide - 1 i[import_java util Scanner class ExeractInformation{ public static void main(String[] args){ Scanner input=nev Scanner (System in: String s: String] into System.out.printin("Format Ex 17000-Harshad Prajapati") 9 System. out print ("Enter prefile name 1 ele input nextLine(Q; u af (aeValia(s))¢ 1 printValidity (2) 8 Enfomextract Info L Syetex. out. printla Syston. out .printia( safe (0!) a Program: Extract Information, Slide - III return false public static String(] extractInfo(string at String{] result=("",*", sult (0J=s. substring (0,2); ie [1]=s\ substring (2/5) result [2]=s. substring (8) ; return result Ty String Methods String coUppercaze() String toLowerCaze( String trin() '@ The toUpperCase() method returns 2 new string with all characters converted to uppercase 18 The toLowerCase() method returns a new string with all characters converted to lowercase. 19 The trim() method removes leading and trailing blank characters, Program: Extract Information, Slide - II System. out. printin("\tSeq vetaze (1); System-out printin("\tWane vsinte (2) No Public scatug void printvatidiey (String #)¢ Systenou ease System.out. printin(*Invalié Valid: "48); s) Public static boo2 eSeherke (8) n isValid (String s){ y A yay Program: Extract Information, Slide - IV String Methods i[Sering replace (char 0140, char ewe) String replaceFiret (String 9145, String nevS) p[String replaceall (String 0145, String news) 4[Sezing(] split (String deiiziter) 19 The replace(oldC, newC); method returns 2 new string with all matching old characters replaced by new characters. 18 The replaceFirst(oldS, new); method returns a new string with the first matching substring (old) replaced by new substring The replaceAll(oldS, newS); method returns 2 new matching substrings (eld) replaced by new substring, ing with all 19 The split(deimiter); method returns an array of strings consisting of the substrings split by the specitied delimiter. a Program: Processing a String, Slide - | i[elass ProceaaStringt 2] “public static void main(Str: Jay 0 ares)¢ and Jay EE are Java String 5 = * Technology System. out.print ("Original string s = System. out printin(s); ae strings System out. printin("After trin(), = Systemout printin("Arter toUpperCase, = = "4s. toUppercaze (0); Systen.out.printin("After toUpperCase, = a Ns. tolewerCase()); System. out.printia("after repiaceAli (\" Jav\",\"Java\") 2. replaceAl] (*Jav"," Java"); System. out.printin("after repiaceAl (\"Jav \",\"Java\") TastIndex0i (char eh) lastindexof (char lastIndexot (String 2) lastIndexOf (String #, int fromIndex) : fromindex); @ All chese methods return -1, if match is not found @ The lastindext hh); returns the last eccurtence of character ch in the invoking string, The lastindexOf(ch,fromlnéex); returns the last occurrence of character ch before fromindex, in the invoking string The lastindexO¥(s); returns the last occurrence of string si invoking string ‘The lastindexO¥(s,fromIndex): returns the ast occurrence of string § before fromindex, in the invoking string 9257 | A A uy | a Program: Processing a String, Slide - III a String Methods Program: Processing a String, Slide - II s.replaceAll("Jav ","Java")); ng dateTin 11/2000 12:30:5 Sout printin(*Splitting string tdateline) Scring{] parts = dateTine.splic(" ") forint 350; i¢pares. lenge System. out. printin("\t"+par String Methods Koning Index of index0d (char eh) indexOf (char ch, int fromIndex); indexOd (String ¢); indexOf (String &, int frosIndex 18 All these methods return -1, if match is not found 12 The indexOf(ch); returns the first occurrence of character ch in the invoking string, 18 The indexOf(ch,fromlndex): returns the first eccurrence of character ch after fromndex, in the invoking string. 18 The indexOr(s); returns the frst accurrence of strings in the invoking string 18 The indexO((s, fromIndex); returns the fist occurrence of string $ after fromlndex, in the invoking string String Methods ifooolean watches (String ing veplaceFirst (String re, String s); ing replaceAll (String re, String 8); ing(] split (String re): 18 For comparing two strings, we use equals() 18 However, matches() provides us te check equality using regular ‘expression RE (pattern) 12 We can also pass regular expression (pa replaceAll() and split() methods ra) t0 replaceFirst(), ay Program: Processing a String with RE, Slide - 1 class ProcessStringhat public static veld main (String[] arge){ String s = “Jay SE and Jav EE are Java Technology String profileNane Prajapat T000-Harshad 17000 Harehad String profileNas 2 Prajapar String daveTine = "1/1/2000 12:30:59"; System System out print ("Original string © out _printin(s) System. out. printin(" replaceAl (Muay [dava\", \nJava\") 5 Sc replaceAl] (*Javi Java", "3 | Program: Processing a String with RE, Slide - III [i= | StringBuffer and StringBuilder © String object is immutable @ StringBuffer and StringBuilder classes allow us to add, insert, oF Append new contents «StringBuffer and StringBuilder provide replacement for String class «@ StringBuffer and StringBuilder are similar StringBuffer is used if isto be accessed among mukiplethresds (Methods are synehroizea) « StringBulger i used if not to be accessed among mulple thresds 1 Following constructors allow us to create StringBuffer object SevingbatFerQ Sringtatfer (ise capac StringBut fer (Sting. ©): Program: Processing a String with RE, Slide - II printin(*replaceall Crjavaiday\", \*Java\") 5 replaceall(*Javal Jav out. printia(profileNamet+ arches (\! profilevanet out. printia(profileName2+ matches (\" #80") profileane2 matches (> .* “ds sys sm out printia(*Splitting string datetime) | Sering(] parts = dateTine. spl for(int i20;i¢parte. lengeh i+ Systen-out -printin("\t"+par BOL LI: tei) I SS ny hy Outline of Presentation @ StringBuffer class Methods of StringBuffer 18 There are many forms of appen() and insert() metheds, ie. for and string We show only widely various primitive types, char array used methods append (String #); insert (int offser delete(inc startindex, ing 5) cringBud fer endIndex) Seringlusfer deletecharat ( index) @ The append() method appends given strings nto the StringBuffer. The insere() method insets the given strings at the specified oft in StringBuffer 1 The delete) method deletes characters from startin to endlndex 1 The deleteCharAt() method deletes character atthe specified index A SS sy a a Methods of StringBuffer StringBuffer endindex , 2|stringbutter void setcn, ‘epiace Gat String 8); verse(): srartindex, ine char ch) 12 The replace() method replaces the characters from startIndex to endlndex-1 with the specified string s. 18 The reverse() method reverses the characters of the Stringuffe. 19 The setCharAt() method sets a new character at the speciied index. Program: Mutiplication Table, Slide. 1[Eiass WalvipiicationTabled Public static void main(String (] arge)¢ ngbuffer buffer = new StringBuffer () int preduct=0 purser Tabi buffer. append buffer append ( Multiplication buffer. append for(int jets buffer. app: buffer. append('\n’) buffer appends fortint pelisecsi jen) Program: Mutiplication Table, Slide- III a [i= | _ttst—“‘“_O™SOOCOCOCC:CCL Methods of StringBuffer cartIadex) 2 startIndex char eharAt (ant index) int Length Ant endIndex); int capacity Q; void setLength (int newLength); void trisTeSize Q; ‘2 The methods: toString(), substring(), charAt(), and length() are similar to that of String class. 4 The capaci); method returns the capac ofthe StringBur The setLength(); method sts ne enth of SvingBtfer ss The timToSize(); method reduces storage size uted fr the StrngButer A sy Program: Mutiplication Table, Slide- 11 product <10) ; Buffer append(” "+product) x else 2 . buffer. append(” “+preduct) buffer. append(" *+"\n") nour printia (butter) Outline of Presentation @ StringTokenizer class a StringTokenizer class StringTokenizer class is available in java.util package StringTokenizer breaks a string into pieces so that information Contained in string can be retrieved and processed, ‘example, we want to separate out all words of a sentence While constructing StringTokenizer, We can specify a set of delimiters, whieh break string into pieces TE Methods of StringTokenizer boolean hasNoreTekens (7 String nex:Token () String nexeTeken (String delim): 18 The hasMoreTokens(); method returns true if there is any token left in the string. It is generally used in loop continue-condition ‘8 The nextToken(); method returns the next token in the string 18 The nextToken(elim); method returns the next token after resetting the delimiter to the specified delim [_—/-/-/-~-~-~=kc_o! Program: Use of StringTokenizer, Slide - || 2 These pieces are calle tokens farang, sng “We World tokens ee The second form i similar to the fst one, but it allows to specify delice ©The third form is similar tothe second one, but allows to specify StringTokenizer class 19 There are three forms of constructors TingTokenizer ( ingTokenizer (3 ingTokenizer (5 boslean tring 8); ng 3, ngs, String delis); String delim returnTokens), 12 The first constructor creates a string tokenizer forthe give string 5 with delimiters as white space characters, ** \t\n\e"* (a space, tab, new line, and carriage return), and delimiters are not returned as whether tokens should be returned of not A ST yy Program: Use of StringTokenizer, Slide - | Tapert java weil SeringTokenizer class UsestyingTekenizer( 3] public static vora main(String() args)< StringTokenizer sti=nee StringTokenizer ("Welcome to Java") Systen.out.printin(*Tokens of "+"Welcome co Java"); vhile(aet- hasMoreTokens ()){ 1| Systemsout println("\t'+ sti nextToxen (0); s| x StringTokonizer st? SeringTokenazer (" : true) en. out. printin(° Token: delimiters of "#"5e3=i while (222. hasNoreTokens ( System-out printin('\t?+ 502. nextToxen (0); s [——_~esststst“‘(C“#NSO#N#C#*“‘(CSNNNCCOC#@’ Program: Use of StringTokenizer, Slide - II a Outline of Presentation @ Command-Line Arguments i TET, SS Program: Command-line Calculator, Slide - | 1[eiass caret 2p] “puviie static void main(String (] arge)¢ int nol, no2: double result char operator Lease use as java Cale operandi operavor pperand?"); syst (a) nol= Integer. parseInt (args [0]); oper ree lil 0) no2= Integer. pargerat (args [2)) Switch (operater){ break: [~~~ . | Program: Command-line Calculator, Slide - III I sy sy Passing Command-Line Arguments 1 Earlier we learned to supply input to our program using two clferent © Using Seanner cass © Using command-tne arguments We provide commanet-ine arguments when we run our program using java interpreter, for example «java Program argOargl srg? These commané-line arguments (arg0 argh arg2) are placed String array and ate passed to main() method: main(String] aes) Inside main() method, these arguments can be accessed using args) args], args(2) Each word separated by white space is considered as one argument If argument itself contains white spaces, then it should be enclosed in double quotes, eg., "Good Morning Program: Command-line Calculator, Slide - II 7 break 3| case's! :resultenoleno? 4 break; 2g case '/?iresult=(nol*1.0) /no2 2 break printia(ae1+ “toperater+" tnoae Summary of key terms String in Java, String class, Immutable string, interned string, string comparison, string ordering String methods StringBuffer and StringBuilder, Methods of StringButer ‘StringTokenizer, methods of StringTokenizer Command-line arguments References @ An Introduction to Java Programming, Y. Daniel Liang, PHI «@ An Introduction to Java Programming, Y. Daniel Liang, Eigth Edition, Prentice Hall

You might also like