String Class Method in Java: Session 3

Before reading this article, please go through the following previous parts of the series:
Now let's move forward to learn about other string methods.
 

Method: Java String valueOf()

 
This method is generally used to convert various types of values into strings. It helps to convert various data types (like int, double, long, float, char, Boolean and so on ) into strings.
 
Basically it returns a string representation of various kinds of data types like above.
 
Let's clarify that with an example.
 
Example
 
In the following example, there are various data types available and for those, this method returns the string.
  1. public class ValueOf   
  2. {  
  3.     public static void main(String args[])   
  4.     {  
  5.         int data = 37;  
  6.         double pointdata = 14.3;  
  7.         String name = "very";  
  8.         boolean decision = false;  
  9.         char[] character =   
  10.         {  
  11.             's''u''n''n'  
  12.         };  
  13.         String str1 = String.valueOf(data);  
  14.         String str2 = String.valueOf(pointdata);  
  15.         String str3 = String.valueOf(name);  
  16.         String str4 = String.valueOf(decision);  
  17.         String str5 = String.valueOf(character);  
  18.         System.out.println(str1 + 301); // concatenates 301 with 37  
  19.         System.out.println(str2 + 124); //concatenates 14.3 with 124  
  20.         System.out.println(str3 + " hot today"); //concatenates 'very' with 'hot today'  
  21.         System.out.println(str4); //returns the string  
  22.         System.out.println(str5 + 'y'); //concatenates all the characters with 'y'  
  23.     }  
  24. }  
Output
 
 
There is another method related to the valueOf() method and that is the copyValueOf() method that also should be discussed for a more thorough understanding.
 

Method: Java String copyValueOf()

 
This method helps to copy an array of characters to the specified string.
 
Note: This method replaces the entire existing string value with the sequence of characters of an array instead of appending the contents in the string.
It has the following two variants:
  • Java String copyValueOf(char[] data)
  • Java String copyValueOf(char[] data, int offset, int count)
The first one just copies the entire array data into the string.
 
The second one copies only the specified string using the specified offset and count values.
 
The offset can be defined as the initial index number in the given array from where the characters need to start copying and the count is the number of characters to be copied.
 
Example
 
In this example, outputs for both variants are shown. We have two strings and an array that is copied to both of the strings using both variant methods.
  1. public class CopyValueOf  
  2. {  
  3.     public static void main(String args[])   
  4.     {  
  5.         char[] alpha =   
  6.         {  
  7.             'c''o''o''l''s''u''n''n''y'  
  8.         };  
  9.         String str1 = "day vs night";  
  10.         String str2 = "one plus one equals two";  
  11.         str1 = str1.copyValueOf(alpha);  
  12.         System.out.println("string1 after applying Ist variant method: " + str1);  
  13.         str1 = str1.copyValueOf(alpha, 4, 3);  
  14.         System.out.println("string1 after applying 2nd variant method: " + str1);  
  15.         str2 = str2.copyValueOf(alpha);  
  16.         System.out.println("string2 after applying Ist variant method: " + str2);  
  17.         str2 = str2.copyValueOf(alpha, 4, 5);  
  18.         System.out.println("string2 after applying 2nd variant method: " + str2);  
  19.     }  
  20. }  
Output
 

 

 
The preceding output shows the copied values for both methods and especially the second method the offset and count values are given. That means offset=4, in other words, start copying after the 4th character and count 3 character, in other words, copy only 3 characters. That will return "sun". Likewise, for offset=4 and count=5 the result is "sunny".
 

Method: Java String intern()

 
This method helps in returning a canonical representation of a string object. The String class in Java privately maintains the pool memory where strings literals are automatically interned. When this method is invoked, it generally searches in the pool memory for the string equal to the given string object. If that string is found there then the string from the pool is returned.
 
The pool memory also has the functionality to save whitespace and to compare faster. If the two strings are to be compared then by using == operator it can be done and it is much faster than equals().
 
Example
 
Here in the following example, both canonical representation, as well as comparison, are shown using this method.
  1. public class Intern   
  2. {  
  3.     public static void main(String args[])   
  4.     {  
  5.         String str1 = "Hey bucky";  
  6.         String str2 = "HEY HOW ARE YOU..??";  
  7.         String str3 = new String("Oh my God");  
  8.         String str4 = "Oh my God";  
  9.         String str5 = str3.intern();  
  10.         String str6 = "at";  
  11.         System.out.println("Canonical form: " + str1); //returns string from pool memory(same string)  
  12.         System.out.println("Canonical form: " + str2); //returns string from pool memory(same string)  
  13.         System.out.println(str3 == str4); //false  
  14.         System.out.println(str4 == str5); //true  
  15.         System.out.println("What" == "Wh" + str6); //strings computed by concatenation at runtime  
  16.         //are newly created,so they are different, hence false  
  17.     }  
  18. }  
Output
 
 

Method: Java String replace()

 
This method is basically used to replace the old characters or charsequence to new characters or charsequence and returns the new string with a replacement of new characters. It has the following four variants:
  • Java String replace(char oldchar, char newchar)

  • Java String replace(charSequence target, charSequence replacement) 
    or 
    Java String replace(String regex, String replacement)

  • Java String replaceFirst(String regex, String replacement)
     
  • Java String replaceAll(charSequence target, charSequence replacement)
    or
    Java String replaceAll(String regex, String replacement)
Let's have a look at the examples for these variants.
 
Example: replace(char oldchar, char newchar)
 
This method replaces only characters.
  1. public class Replace   
  2. {  
  3.     public static void main(String args[])   
  4.     {  
  5.         String str1 = "there are seven days in a week";  
  6.         String str2 = "there are twelve months in a year";  
  7.         System.out.println("String after replacing all 'e' to '0': " + str1.replace('e''o')); //replaces all 'e' to 'o'  
  8.         System.out.println("String after replacing all 't' to 'p': " + str2.replace('t''p')); //replaces all 't' to ‘p'  
  9.     }  
  10. }  
Output
 
 
Example: replace(charSequence target, charSequence replacement)

or

Java String replace(String regex, String replacement)
(( This method replaces all charSequences by the given charSequence. ))
 
and
 
Java String replaceFirst(String regex, String replacement)
(( This method replaces only the first charSequence and the rest remains unchanged. ))
 
Let's see examples for both.
  1. public class ReplaceAndReplaceFirst   
  2. {  
  3.     public static void main(String args[])   
  4.     {  
  5.         String str1 = "two plus two equals four";  
  6.         String str2 = "many many happy returns of the day";  
  7.         System.out.println("String after replacing all 'two' to 'one': " + str1.replace("two""one")); //replaces all 'two' to 'one'  
  8.         System.out.println("String after replacing all 'many' to 'plenty': " + str2.replace("many""plenty")); //replaces all 'many' to 'plenty'  
  9.         System.out.println();  
  10.         System.out.println("String after replacing only first 'two' to 'one': " + str1.replaceFirst("two""one")); //replaces first 'two' to 'one'  
  11.         System.out.println("String after replacing only first 'many' to 'plenty': " + str2.replaceFirst("many""plenty")); //replaces first 'many' to 'plenty'  
  12.     }  
  13. }  
Output
 
 
 
In the preceding output, we can observe the difference that is specified above.
 
Example: Java String replaceAll(charSequence target, charSequence replacement)
 
or
 
Java String replaceAll(String regex, String replacement) 
(( This method can do all the functions as the preceding methods can do, in other words, old to a new character, can replace charSequence (word) also can remove white spaces. ))
 
Have a look at the following example.
  1. public class ReplaceAll   
  2. {  
  3.     public static void main(String args[])   
  4.     {  
  5.         String str1 = "sun burn turn";  
  6.         String str2 = "try try again";  
  7.         String str3 = "Rainy Season Is Better";  
  8.         System.out.println("String after replacing all 'u' to 'o': " + str1.replaceAll("u""o")); //replaces all 'u' to 'o'  
  9.         System.out.println("String after replacing all 'try' to 'cry': " + str2.replaceAll("try""cry")); //replaces all 'try' to 'cry'  
  10.         System.out.println("String after replacing all 'spaces' to 'no space': " + str3.replaceAll("\\s""")); //replaces all 'spaces' to 'no spaces'  
  11.     }  
  12. }  
Output
 
 
 
In the preceding output, we can observe all the operations are done by this method.
 
Want more the follow the link given below.
 
Thank you, keep learning and sharing.