WordPress.com



Java StringJava String HandlingHow to create string object String literalnew keywordJava String provides a lot of concepts that can be performed on a string such as compare, concat, equals, split, length, replace, compareTo, intern, substring etc. In java, string is basically an object that represents sequence of char values.An array of characters works same as java string. For example:char[]?ch={'j','a','v','a','t','p','o','i','n','t'};??String?s=new?String(ch);??is same as:String?s="javatpoint";??The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.The java String is immutable i.e. it cannot be changed but a new instance is created. For mutable class, you can use StringBuffer and StringBuilder class.We will discuss about immutable string later. Let's first understand what is string in java and how to create the string object.What is String in javaGenerally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. String class is used to create string object.How to create String object?There are two ways to create String object: By string literalBy new keyword1) String LiteralJava String literal is created by using double quotes. For Example:String?s="welcome";??Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example: String?s1="Welcome";??String?s2="Welcome";//will?not?create?new?instance??In the above example only one object will be created. Firstly JVM will not find any string object with the value "Welcome" in string constant pool, so it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create new object but will return the reference to the same instance. Note: String objects are stored in a special memory area known as string constant pool.Why java uses concept of string literal?To make Java more memory efficient (because no new objects are created if it exists already in string constant pool). 2) By new keywordString?s=new?String("Welcome");//creates?two?objects?and?one?reference?variable??In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool). Java String Examplepublic?class?StringExample{??public?static?void?main(String?args[]){??String?s1="java";//creating?string?by?java?string?literal????char?ch[]={'s','t','r','i','n','g','s'};??String?s2=new?String(ch);//converting?char?array?to?string????String?s3=new?String("example");//creating?java?string?by?new?keyword????System.out.println(s1);??System.out.println(s2);??System.out.println(s3);??}}??Test it Now javastringsexampleJava String class methodsThe java.lang.String class provides many useful methods to perform operations on sequence of char values.No.MethodDescription1char charAt(int index)returns char value for the particular index2int length()returns string length3static String format(String format, Object... args)returns formatted string4static String format(Locale l, String format, Object... args)returns formatted string with given locale5String substring(int beginIndex)returns substring for given begin index6String substring(int beginIndex, int endIndex)returns substring for given begin index and end index7boolean contains(CharSequence s)returns true or false after matching the sequence of char value8static String join(CharSequence delimiter, CharSequence... elements)returns a joined string9static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)returns a joined string10boolean equals(Object another)checks the equality of string with object11boolean isEmpty()checks if string is empty12String concat(String str)concatinates specified string13String replace(char old, char new)replaces all occurrences of specified char value14String replace(CharSequence old, CharSequence new)replaces all occurrences of specified CharSequence15String trim()returns trimmed string omitting leading and trailing spaces16String split(String regex)returns splitted string matching regex17String split(String regex, int limit)returns splitted string matching regex and limit18String intern()returns interned string19int indexOf(int ch)returns specified char value index20int indexOf(int ch, int fromIndex)returns specified char value index starting with given index21int indexOf(String substring)returns specified substring index22int indexOf(String substring, int fromIndex)returns specified substring index starting with given index23String toLowerCase()returns string in lowercase.24String toLowerCase(Locale l)returns string in lowercase using specified locale.25String toUpperCase()returns string in uppercase.26String toUpperCase(Locale l)returns string in uppercase using specified locale.Do You Know ? Why String objects are immutable?How to create an immutable class?What is string constant pool?What code is written by the compiler if you concat any string by + (string concatenation operator)?What is the difference between StringBuffer and StringBuilder class?Immutable String in JavaIn java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.Once string object is created its data or state can't be changed but a new string object is created.Let's try to understand the immutability concept by the example given below:class?Testimmutablestring{???public?static?void?main(String?args[]){?????String?s="Sachin";?????s.concat("?Tendulkar");//concat()?method?appends?the?string?at?the?end?????System.out.println(s);//will?print?Sachin?because?strings?are?immutable?objects???}??}??Test it Now Output:SachinNow it can be understood by the diagram given below. Here Sachin is not changed but a new object is created with sachintendulkar. That is why string is known as immutable.As you can see in the above figure that two objects are created but s reference variable still refers to "Sachin" not to "Sachin Tendulkar".But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For example: class?Testimmutablestring1{???public?static?void?main(String?args[]){?????String?s="Sachin";?????s=s.concat("?Tendulkar");?????System.out.println(s);???}??}??Test it Now Output:Sachin TendulkarIn such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not modified.Why string objects are immutable in java?Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java. String comparison in JavaWe can compare two given strings on the basis of content and reference.It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.There are three ways to compare String objects:By equals() methodBy = = operatorBy compareTo() method1) By equals() methodequals() method compares the original content of the string.It compares values of string for equality.String class provides two methods: public boolean equals(Object another){} compares this string to the specified object.public boolean equalsIgnoreCase(String another){} compares this String to another String, ignoring case.class?Teststringcomparison1{???public?static?void?main(String?args[]){????????String?s1="Sachin";?????String?s2="Sachin";?????String?s3=new?String("Sachin");?????String?s4="Saurav";???????System.out.println(s1.equals(s2));//true?????System.out.println(s1.equals(s3));//true?????System.out.println(s1.equals(s4));//false???}??}??Test it Now Output:true true false//Example?of?equalsIgnoreCase(String)?method??class?Teststringcomparison2{???public?static?void?main(String?args[]){????????String?s1="Sachin";?????String?s2="SACHIN";???????System.out.println(s1.equals(s2));//false?????System.out.println(s1.equalsIgnoreCase(s3));//true???}??}??Test it Now Output:false true2) By == operatorThe = = operator compares references not values. //<b><i>Example?of?==?operator</i></b>????class?Teststringcomparison3{???public?static?void?main(String?args[]){????????String?s1="Sachin";?????String?s2="Sachin";?????String?s3=new?String("Sachin");???????System.out.println(s1==s2);//true?(because?both?refer?to?same?instance)?????System.out.println(s1==s3);//false(because?s3?refers?to?instance?created?in?nonpool)???}??}??Test it Now Output:true false3) By compareTo() method:compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than. Suppose s1 and s2 are two string variables.If:s1 == s2 :0s1 > s2 ? :positive values1 < s2 ? :negative value//<b><i>Example?of?compareTo()?method:</i></b>????class?Teststringcomparison4{???public?static?void?main(String?args[]){????????String?s1="Sachin";?????String?s2="Sachin";?????String?s3="Ratan";???????System.out.println(pareTo(s2));//0?????System.out.println(pareTo(s3));//1(because?s1>s3)?????System.out.println(pareTo(s1));//-1(because?s3?<?s1?)???}??}??Test it Now Output:0 1 -1String Concatenation in JavaConcating strings form a new string i.e. the combination of multiple strings.There are two ways to concat string objects:By + (string concatenation) operatorBy concat() method1) By + (string concatenation) operatorString concatenation operator is used to add strings.For Example://Example?of?string?concatenation?operator????class?TestStringConcatenation1{???public?static?void?main(String?args[]){????????String?s="Sachin"+"?Tendulkar";?????System.out.println(s);//Sachin?Tendulkar???}??}??Test it Now Output:Sachin TendulkarThe compiler transforms this to:String?s=(new?StringBuilder()).append("Sachin").append("?Tendulkar).toString();??String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.String concatenation operator produces a new string by appending the second operand onto the end of the first operand.The string concatenation operator can concat not only string but primitive values also.For Example: class?TestStringConcatenation2{???public?static?void?main(String?args[]){????????String?s=50+30+"Sachin"+40+40;?????System.out.println(s);//80Sachin4040???}??}??Test it Now Output:80Sachin4040Note:If either operand is a string, the resulting operation will be string concatenation. If both operands are numbers, the operator will perform an addition. 2) By concat() methodconcat() method concatenates the specified string to the end of current string. Syntax:public String concat(String another){}//<b><i>Example?of?concat(String)?method</i></b>????class?TestStringConcatenation3{???public?static?void?main(String?args[]){????????String?s1="Sachin?";?????String?s2="Tendulkar";???????String?s3=s1.concat(s2);???????System.out.println(s3);//Sachin?Tendulkar????}??}??Test it Now Output:Sachin TendulkarSubstring in JavaA part of string is called substring. In other words, substring is a subset of another string.In case of substring startIndex starts from 0 and endIndex starts from 1 or startIndex is inclusive and endIndex is exclusive.You can get substring from the given String object by one of the two methods:public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).public String substring(int startIndex,int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.In case of string:startIndex:starts from index 0(inclusive). endIndex:starts from index 1(exclusive). Example of java substring//Example?of?substring()?method????public?class?TestSubstring{???public?static?void?main(String?args[]){????????String?s="Sachin?Tendulkar";?????System.out.println(s.substring(6));//Tendulkar?????System.out.println(s.substring(0,6));//Sachin???}??}??Test it Now Output:Tendulkar SachinJava String class methodsThe java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based or mobile application.Let's see the important methods of String class.Java String toUpperCase() and toLowerCase() methodThe java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter.String?s="Sachin";??System.out.println(s.toUpperCase());//SACHIN??System.out.println(s.toLowerCase());//sachin??System.out.println(s);//Sachin(no?change?in?original)??Test it Now SACHINsachinSachinJava String trim() methodThe string trim() method eliminates white spaces before and after string.String?s="??Sachin??";??System.out.println(s);//??Sachin????System.out.println(s.trim());//Sachin??Test it Now Sachin SachinJava String startsWith() and endsWith() methodString?s="Sachin";???System.out.println(s.startsWith("Sa"));//true???System.out.println(s.endsWith("n"));//true??Test it Now truetrueJava String charAt() methodThe string charAt() method returns a character at specified index.String?s="Sachin";??System.out.println(s.charAt(0));//S??System.out.println(s.charAt(3));//h??Test it Now ShJava String length() methodThe string length() method returns length of the string.String?s="Sachin";??System.out.println(s.length());//6??Test it Now 6Java String intern() methodA pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. String?s=new?String("Sachin");??String?s2=s.intern();??System.out.println(s2);//Sachin??Test it Now SachinJava String valueOf() methodThe string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string.int?a=10;??String?s=String.valueOf(a);??System.out.println(s+10);??1010StringBuffer class:The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class is same as String except it is mutable i.e. it can be changed. Note: StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously .So it is safe and will result in an monly used Constructors of StringBuffer class:StringBuffer(): creates an empty string buffer with the initial capacity of 16.StringBuffer(String str): creates a string buffer with the specified string.StringBuffer(int capacity): creates an empty string buffer with the specified capacity as monly used methods of StringBuffer class:public synchronized StringBuffer append(String s): is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex.public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the string from specified startIndex and endIndex.public synchronized StringBuffer reverse(): is used to reverse the string.public int capacity(): is used to return the current capacity.public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum.public char charAt(int index): is used to return the character at the specified position.public int length(): is used to return the length of the string i.e. total number of characters.public String substring(int beginIndex): is used to return the substring from the specified beginIndex.public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex.What is mutable string?A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string. simple example of StringBuffer class by append() methodThe append() method concatenates the given argument with this string. class?A{??public?static?void?main(String?args[]){????StringBuffer?sb=new?StringBuffer("Hello?");??sb.append("Java");//now?original?string?is?changed????System.out.println(sb);//prints?Hello?Java??}??}??Example of insert() method of StringBuffer classThe insert() method inserts the given string with this string at the given position. class?A{??public?static?void?main(String?args[]){????StringBuffer?sb=new?StringBuffer("Hello?");??sb.insert(1,"Java");//now?original?string?is?changed????System.out.println(sb);//prints?HJavaello??}??}??Example of replace() method of StringBuffer classThe replace() method replaces the given string from the specified beginIndex and endIndex. class?A{??public?static?void?main(String?args[]){????StringBuffer?sb=new?StringBuffer("Hello");??sb.replace(1,3,"Java");????System.out.println(sb);//prints?HJavalo??}??}??Example of delete() method of StringBuffer classThe delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex. class?A{??public?static?void?main(String?args[]){????StringBuffer?sb=new?StringBuffer("Hello");??sb.delete(1,3);????System.out.println(sb);//prints?Hlo??}??}??Example of reverse() method of StringBuffer classThe reverse() method of StringBuilder class reverses the current string. class?A{??public?static?void?main(String?args[]){????StringBuffer?sb=new?StringBuffer("Hello");??sb.reverse();????System.out.println(sb);//prints?olleH??}??}??Example of capacity() method of StringBuffer classThe capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. class?A{??public?static?void?main(String?args[]){????StringBuffer?sb=new?StringBuffer();??System.out.println(sb.capacity());//default?16????sb.append("Hello");??System.out.println(sb.capacity());//now?16????sb.append("java?is?my?favourite?language");??System.out.println(sb.capacity());//now?(16*2)+2=34?i.e?(oldcapacity*2)+2??}??}??Example of ensureCapacity() method of StringBuffer classThe ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. class?A{??public?static?void?main(String?args[]){????StringBuffer?sb=new?StringBuffer();??System.out.println(sb.capacity());//default?16????sb.append("Hello");??System.out.println(sb.capacity());//now?16????sb.append("java?is?my?favourite?language");??System.out.println(sb.capacity());//now?(16*2)+2=34?i.e?(oldcapacity*2)+2????sb.ensureCapacity(10);//now?no?change??System.out.println(sb.capacity());//now?34????sb.ensureCapacity(50);//now?(34*2)+2??System.out.println(sb.capacity());//now?70????}??}??StringBuilder class:The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK1.5. Commonly used Constructors of StringBuilder class:StringBuilder(): creates an empty string Builder with the initial capacity of 16.StringBuilder(String str): creates a string Builder with the specified string.StringBuilder(int length): creates an empty string Builder with the specified capacity as monly used methods of StringBuilder class:public StringBuilder append(String s): is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.public StringBuilder insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.public StringBuilder replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex.public StringBuilder delete(int startIndex, int endIndex): is used to delete the string from specified startIndex and endIndex.public StringBuilder reverse(): is used to reverse the string.public int capacity(): is used to return the current capacity.public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum.public char charAt(int index): is used to return the character at the specified position.public int length(): is used to return the length of the string i.e. total number of characters.public String substring(int beginIndex): is used to return the substring from the specified beginIndex.public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex.simple program of StringBuilder class by append() methodThe append() method concatenates the given argument with this string. class?A{??public?static?void?main(String?args[]){????StringBuilder?sb=new?StringBuilder("Hello?");??sb.append("Java");//now?original?string?is?changed????System.out.println(sb);//prints?Hello?Java??}??}??Example of insert() method of StringBuilder classThe insert() method inserts the given string with this string at the given position. class?A{??public?static?void?main(String?args[]){????StringBuilder?sb=new?StringBuilder("Hello?");??sb.insert(1,"Java");//now?original?string?is?changed????System.out.println(sb);//prints?HJavaello??}??}??Example of replace() method of StringBuilder classThe replace() method replaces the given string from the specified beginIndex and endIndex. class?A{??public?static?void?main(String?args[]){????StringBuilder?sb=new?StringBuilder("Hello");??sb.replace(1,3,"Java");????System.out.println(sb);//prints?HJavalo??}??}??Example of delete() method of StringBuilder classThe delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex. class?A{??public?static?void?main(String?args[]){????StringBuilder?sb=new?StringBuilder("Hello");??sb.delete(1,3);????System.out.println(sb);//prints?Hlo??}??}??Example of reverse() method of StringBuilder classThe reverse() method of StringBuilder class reverses the current string. class?A{??public?static?void?main(String?args[]){????StringBuilder?sb=new?StringBuilder("Hello");??sb.reverse();????System.out.println(sb);//prints?olleH??}??}??Example of capacity() method of StringBuilder classThe capacity() method of StringBuilder class returns the current capacity of the Builder. The default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. class?A{??public?static?void?main(String?args[]){????StringBuilder?sb=new?StringBuilder();??System.out.println(sb.capacity());//default?16????sb.append("Hello");??System.out.println(sb.capacity());//now?16????sb.append("java?is?my?favourite?language");??System.out.println(sb.capacity());//now?(16*2)+2=34?i.e?(oldcapacity*2)+2??}??}??Example of ensureCapacity() method of StringBuilder classThe ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. class?A{??public?static?void?main(String?args[]){????StringBuilder?sb=new?StringBuilder();??System.out.println(sb.capacity());//default?16????sb.append("Hello");??System.out.println(sb.capacity());//now?16????sb.append("java?is?my?favourite?language");??System.out.println(sb.capacity());//now?(16*2)+2=34?i.e?(oldcapacity*2)+2????sb.ensureCapacity(10);//now?no?change??System.out.println(sb.capacity());//now?34????sb.ensureCapacity(50);//now?(34*2)+2??System.out.println(sb.capacity());//now?70????}??}??How to create Immutable class?There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members as the example given below: Example to create Immutable classIn this example, we have created a final class named Employee. It have one final datamember, a parameterized constructor and getter method. public?final?class?Employee{??final?String?pancardNumber;????public?Employee(String?pancardNumber){??this.pancardNumber=pancardNumber;??}????public?String?getPancardNumber(){??return?pancardNumber;??}????}??The above class is immutable because: The instance variable of the class is final i.e. we cannot change the value of it after creating an object.The class is final so we cannot create the subclass.There is no setter methods i.e. we have no option to change the value of the instance variable.These points makes this class as immutable. Understanding toString() method If you want to represent any object as a string, toString() method comes into existence.The toString() method returns the string representation of the object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.Advantage of the toString() method By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.Understanding problem without toString() methodLet's see the simple code that prints reference.class?Student{???int?rollno;???String?name;???String?city;?????Student(int?rollno,?String?name,?String?city){???this.rollno=rollno;???this.name=name;???this.city=city;???}?????public?static?void?main(String?args[]){?????Student?s1=new?Student(101,"Raj","lucknow");?????Student?s2=new?Student(102,"Vijay","ghaziabad");??????????System.out.println(s1);//compiler?writes?here?s1.toString()?????System.out.println(s2);//compiler?writes?here?s2.toString()???}??}??Output:Student@1fee6fc Student@1eed786As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:Example of toString() methodNow let's see the real example of toString() method.class?Student{???int?rollno;???String?name;???String?city;?????Student(int?rollno,?String?name,?String?city){???this.rollno=rollno;???this.name=name;???this.city=city;???}??????public?String?toString(){//overriding?the?toString()?method????return?rollno+"?"+name+"?"+city;???}???public?static?void?main(String?args[]){?????Student?s1=new?Student(101,"Raj","lucknow");?????Student?s2=new?Student(102,"Vijay","ghaziabad");??????????System.out.println(s1);//compiler?writes?here?s1.toString()?????System.out.println(s2);//compiler?writes?here?s2.toString()???}??}??download this example of toString method Output:101 Raj lucknow 102 Vijay ghaziabadStringTokenizer in JavaStringTokenizerMethods of StringTokenizerExample of StringTokenizerThe java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string.It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.Constructors of StringTokenizer classThere are 3 constructors defined in the StringTokenizer class.ConstructorDescriptionStringTokenizer(String str)creates StringTokenizer with specified string.StringTokenizer(String str, String delim)creates StringTokenizer with specified string and delimeter.StringTokenizer(String str, String delim, boolean returnValue)creates StringTokenizer with specified string, delimeter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.Methods of StringTokenizer classThe 6 useful methods of StringTokenizer class are as follows:Public methodDescriptionboolean hasMoreTokens()checks if there is more tokens available.String nextToken()returns the next token from the StringTokenizer object.String nextToken(String delim)returns the next token based on the delimeter.boolean hasMoreElements()same as hasMoreTokens() method.Object nextElement()same as nextToken() but its return type is Object.int countTokens()returns the total number of tokens.Simple example of StringTokenizer classLet's see the simple example of StringTokenizer class that tokenizes a string "my name is khan" on the basis of whitespace.import?java.util.StringTokenizer;??public?class?Simple{???public?static?void?main(String?args[]){?????StringTokenizer?st?=?new?StringTokenizer("my?name?is?khan","?");???????while?(st.hasMoreTokens())?{???????????System.out.println(st.nextToken());???????}?????}??}??Output:my name is khanExample of nextToken(String delim) method of StringTokenizer classimport?java.util.*;????public?class?Test?{?????public?static?void?main(String[]?args)?{?????????StringTokenizer?st?=?new?StringTokenizer("my,name,is,khan");????????????????//?printing?next?token????????System.out.println("Next?token?is?:?"?+?st.nextToken(","));?????}??????}??Output:Next token is : myStringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).Java RegexThe Java Regex or Regular Expression is an API to define pattern for searching or manipulating strings.It is widely used to define constraint on strings such as password and email validation. After learning java regex tutorial, you will be able to test your own regular expressions by the Java Regex Tester Tool.Java Regex API provides 1 interface and 3 classes in java.util.regex package.java.util.regex packageIt provides following classes and interface for regular expressions. The Matcher and Pattern classes are widely used in java regular expression.MatchResult interfaceMatcher classPattern classPatternSyntaxException classMatcher classIt implements MatchResult interface. It is a regex engine i.e. used to perform match operations on a character sequence.No.MethodDescription1boolean matches()test whether the regular expression matches the pattern.2boolean find()finds the next expression that matches the pattern.3boolean find(int start)finds the next expression that matches the pattern from the given start number.Pattern classIt is the compiled version of a regular expression. It is used to define a pattern for the regex engine.No.MethodDescription1static Pattern compile(String regex)compiles the given regex and return the instance of pattern.2Matcher matcher(CharSequence input)creates a matcher that matches the given input with pattern.3static boolean matches(String regex, CharSequence input)It works as the combination of compile and matcher methods. It compiles the regular expression and matches the given input with the pattern.4String[] split(CharSequence input)splits the given input string around matches of given pattern. 5String pattern()returns the regex pattern.Example of Java Regular ExpressionsThere are three ways to write the regex example in java.import?java.util.regex.*;??public?class?RegexExample1{??public?static?void?main(String?args[]){??//1st?way??Pattern?p?=?pile(".s");//.?represents?single?character??Matcher?m?=?p.matcher("as");??boolean?b?=?m.matches();????//2nd?way??boolean?b2=pile(".s").matcher("as").matches();????//3rd?way??boolean?b3?=?Pattern.matches(".s",?"as");????System.out.println(b+"?"+b2+"?"+b3);??}}??Test it Now Outputtrue true trueRegular Expression . ExampleThe . (dot) represents a single character.import?java.util.regex.*;??class?RegexExample2{??public?static?void?main(String?args[]){??System.out.println(Pattern.matches(".s",?"as"));//true?(2nd?char?is?s)??System.out.println(Pattern.matches(".s",?"mk"));//false?(2nd?char?is?not?s)??System.out.println(Pattern.matches(".s",?"mst"));//false?(has?more?than?2?char)??System.out.println(Pattern.matches(".s",?"amms"));//false?(has?more?than?2?char)??System.out.println(Pattern.matches("..s",?"mas"));//true?(3rd?char?is?s)??}}??Test it Now Regex Character classesNo.Character ClassDescription1[abc]a, b, or c (simple class)2[^abc]Any character except a, b, or c (negation)3[a-zA-Z]a through z or A through Z, inclusive (range)4[a-d[m-p]]a through d, or m through p: [a-dm-p] (union)5[a-z&&[def]]d, e, or f (intersection)6[a-z&&[^bc]]a through z, except for b and c: [ad-z] (subtraction)7[a-z&&[^m-p]]a through z, and not m through p: [a-lq-z](subtraction)Regular Expression Character classes Exampleimport?java.util.regex.*;??class?RegexExample3{??public?static?void?main(String?args[]){??System.out.println(Pattern.matches("[amn]",?"abcd"));//false?(not?a?or?m?or?n)??System.out.println(Pattern.matches("[amn]",?"a"));//true?(among?a?or?m?or?n)??System.out.println(Pattern.matches("[amn]",?"ammmna"));//false?(m?and?a?comes?more?than?once)??}}??Test it Now Regex QuantifiersThe quantifiers specify the number of occurrences of a character. RegexDescriptionX?X occurs once or not at allX+X occurs once or more timesX*X occurs zero or more timesX{n}X occurs n times onlyX{n,}X occurs n or more timesX{y,z}X occurs at least y times but less than z timesRegular Expression Character classes and Quantifiers Exampleimport?java.util.regex.*;??class?RegexExample4{??public?static?void?main(String?args[]){??System.out.println("??quantifier?....");??System.out.println(Pattern.matches("[amn]?",?"a"));//true?(a?or?m?or?n?comes?one?time)??System.out.println(Pattern.matches("[amn]?",?"aaa"));//false?(a?comes?more?than?one?time)??System.out.println(Pattern.matches("[amn]?",?"aammmnn"));//false?(a?m?and?n?comes?more?than?one?time)??System.out.println(Pattern.matches("[amn]?",?"aazzta"));//false?(a?comes?more?than?one?time)??System.out.println(Pattern.matches("[amn]?",?"am"));//false?(a?or?m?or?n?must?come?one?time)????System.out.println("+?quantifier?....");??System.out.println(Pattern.matches("[amn]+",?"a"));//true?(a?or?m?or?n?once?or?more?times)??System.out.println(Pattern.matches("[amn]+",?"aaa"));//true?(a?comes?more?than?one?time)??System.out.println(Pattern.matches("[amn]+",?"aammmnn"));//true?(a?or?m?or?n?comes?more?than?once)??System.out.println(Pattern.matches("[amn]+",?"aazzta"));//false?(z?and?t?are?not?matching?pattern)????System.out.println("*?quantifier?....");??System.out.println(Pattern.matches("[amn]*",?"ammmna"));//true?(a?or?m?or?n?may?come?zero?or?more?times)????}}??Test it Now Regex MetacharactersThe regular expression metacharacters work as a short codes.RegexDescription.Any character (may or may not match terminator)\dAny digits, short of [0-9]\DAny non-digit, short for [^0-9]\sAny whitespace character, short for [\t\n\x0B\f\r]\SAny non-whitespace character, short for [^\s]\wAny word character, short for [a-zA-Z_0-9]\WAny non-word character, short for [^\w]\bA word boundary\BA non word boundaryRegular Expression Metacharacters Exampleimport?java.util.regex.*;??class?RegexExample5{??public?static?void?main(String?args[]){??System.out.println("metacharacters?d....");\\d?means?digit????System.out.println(Pattern.matches("\\d",?"abc"));//false?(non-digit)??System.out.println(Pattern.matches("\\d",?"1"));//true?(digit?and?comes?once)??System.out.println(Pattern.matches("\\d",?"4443"));//false?(digit?but?comes?more?than?once)??System.out.println(Pattern.matches("\\d",?"323abc"));//false?(digit?and?char)????System.out.println("metacharacters?D....");\\D?means?non-digit????System.out.println(Pattern.matches("\\D",?"abc"));//false?(non-digit?but?comes?more?than?once)??System.out.println(Pattern.matches("\\D",?"1"));//false?(digit)??System.out.println(Pattern.matches("\\D",?"4443"));//false?(digit)??System.out.println(Pattern.matches("\\D",?"323abc"));//false?(digit?and?char)??System.out.println(Pattern.matches("\\D",?"m"));//true?(non-digit?and?comes?once)????System.out.println("metacharacters?D?with?quantifier....");??System.out.println(Pattern.matches("\\D*",?"mak"));//true?(non-digit?and?may?come?0?or?more?times)????}}??Test it Now Regular Expression Question 1/*Create?a?regular?expression?that?accepts?alpha?numeric?characters?only.?Its?length?must?be?6?characters?long?only.*/????import?java.util.regex.*;??class?RegexExample6{??public?static?void?main(String?args[]){??System.out.println(Pattern.matches("[a-zA-Z0-9]{6}",?"arun32"));//true??System.out.println(Pattern.matches("[a-zA-Z0-9]{6}",?"kkvarun32"));//false?(more?than?6?char)??System.out.println(Pattern.matches("[a-zA-Z0-9]{6}",?"JA2Uk2"));//true??System.out.println(Pattern.matches("[a-zA-Z0-9]{6}",?"arun$2"));//false?($?is?not?matched)??}}??Test it Now Regular Expression Question 2/*Create?a?regular?expression?that?accepts?10?digit?numeric?characters??starting?with?7,?8?or?9?only.*/????import?java.util.regex.*;??class?RegexExample7{??public?static?void?main(String?args[]){??System.out.println("by?character?classes?and?quantifiers?...");??System.out.println(Pattern.matches("[789]{1}[0-9]{9}",?"9953038949"));//true??System.out.println(Pattern.matches("[789][0-9]{9}",?"9953038949"));//true????System.out.println(Pattern.matches("[789][0-9]{9}",?"99530389490"));//false?(11?characters)??System.out.println(Pattern.matches("[789][0-9]{9}",?"6953038949"));//false?(starts?from?6)??System.out.println(Pattern.matches("[789][0-9]{9}",?"8853038949"));//true????System.out.println("by?metacharacters?...");??System.out.println(Pattern.matches("[789]{1}\\d{9}",?"8853038949"));//true??System.out.println(Pattern.matches("[789]{1}\\d{9}",?"3853038949"));//false?(starts?from?3)????}}?? ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download