How to use String in Java

Java String

 
A String is a sequence of characters or in order words, a String is an array of characters, where all the characters are stored in a sequence in contiguous memory locations.
 
The difference between String and Character Array is that a string is suffixed by '\0', unlike Character Array.
 
Difference between Character and String is that character is represented by single quotes (' ') and String is represented by double quotes (" ")
 
Java String is part of java.lang package
 

Features of Java String 

  1. Compilation creates unique strings. At compile time, strings are resolved as far as possible. This includes applying the concatenation operator and converting other literals to strings. So “CSharp” and (“C”+"Sharp") both get resolved at compile time to the same string and are identical objects in the class string pool. 
  2. Because String objects are immutable (i.e. they cannot be modified), a substring operation doesn’t need to copy the entire underlying sequence of characters. Instead, a substring can use the same char array as the original string and simply refer to a different start point and endpoint in the char array. 
  3. Strings are implemented in the JDK as an internal char array with index offsets (actually a start offset and a character count). This basic structure is extremely unlikely to be changed in any version of Java.

Shortcomings of Java String 

  1. It is not possible to add behavior (i.e. custom functionalities) to String for your own needs.
  2. The only way to impose efficient String Manipulation is to copy the characters into your array and manipulate them directly
  3. Char arrays are faster to process directly.

StringBuffer 

  1. The close relationship with StringBuffer allows Strings to reference the same char array used by the StringBuffer. For typical practice, when you use a StringBuffer to manipulate and append characters and data types and then convert the final result to a String.
  2. The StringBuffer provides efficient mechanisms for growing, inserting, appending, altering, and other types of String manipulation. The resulting String then efficiently references the same char array with no extra character copying.
  3. If the StringBuffer object is subsequently altered, the char array in that StringBuffer is copied into a new char array that is now referenced by the StringBuffer. The String object retains the reference to the previously shared char array. This means that copying overhead can occur at unexpected points in the application.
  4. Instead of the copying occurring at the toString( ) method call, any subsequent alteration of the StringBuffer causes a new char array to be created and an array copy to be performed. To make the copying overhead occur at predictable times, you could explicitly execute some method that makes the copying occur, such as StringBuffer.setLength( ). This allows StringBuffer to be reused with a more predictable performance.
  5. The tight coupling with StringBuffer can lead to unexpectedly high memory usage. When StringBuffer.toString( ) creates a String, the current underlying array holds the string, regardless of the size of the array (i.e., the capacity of the StringBuffer).
  6. For example, a StringBuffer with a capacity of 10,000 characters can build a string of 10 characters. However, 10-character String continues to use a 10,000-char array to store the 10 characters. If the StringBuffer is now reused to create another 10-character string, the StringBuffer first creates a new internal 10,000-char array to build the string with; then the new String also uses that 10,000-char array to store the 10 characters. This process can continue indefinitely, using vast amounts of memory were not expected.
  1. import java.io.*;  
  2. import java.lang.*;  
  3.   
  4. class Csharpcorner  
  5. {  
  6.     public static void main(String[] args)  
  7.     {  
  8.         String s = "CSharpCorner";  
  9.           
  10.         String str = new String ("CSharpCorner");  
  11.           
  12.     }  

The above code demonstrates the two ways of declaring String objects. Firstly, we are just assigning the value to the string variable "s", in the second way we are using the String constructor to create a String variable named "str"
 

Java String Constructors

  1.  String(byte[] byte_arr)

    Construct a new String by decoding the byte array. It uses the platform’s default character set for decoding.
    1. import java.io.*;  
    2. import java.lang.*;  
    3.   
    4. class Csharpcorner  
    5. {  
    6.     public static void main(String[] args)  
    7.     {  
    8.         String str = new String ("CSharpCorner");  
    9.           
    10.     }  
    11. }
  2. String(byte[] byte_arr, Charset char_set) 

    Construct a new String by decoding the byte array. It uses the char_set for decoding.
    1. import java.io.*;  
    2. import java.lang.*;  
    3.   
    4. class Csharpcorner  
    5. {  
    6.     public static void main(String[] args)  
    7.     {  
    8.         byte[] b_arr = {67831149711411267111114110101114};  
    9.         Charset cs = Charset.defaultCharset();  
    10.         String s_byte_char = new String(b_arr, cs);  
    11.         //CSharpCorner  
    12.           
    13.     }  

    In the above code, we are converting the given byte stream into a String using the Default Charset decoding.
    My system has the following features of Charset Decoding:
    Default Charset=ISO-8859-1
    file.encoding=Latin-1
    Default Charset=ISO-8859-1
    Default Charset in Use=ISO8859_1


  3. String(byte[] byte_arr, String char_set_name)

    Construct a new String by decoding the byte array. It uses the char_set_name for decoding.
    1. import java.io.*;  
    2. import java.lang.*;  
    3.   
    4. class Csharpcorner  
    5. {  
    6.     public static void main(String[] args)  
    7.     {  
    8.         byte[] b_arr = {67831149711411267111114110101114};  
    9.           
    10.         String s = new String(b_arr, "US-ASCII");  
    11.         //CSharpCorner  
    12.           
    13.     }  

    The above code and the previous code are performing the same functions, with only one difference that in the above code are explicitly providing the name of the Decoding, whereas in the previous we left it on to the system to decide which decoding to use

  4. String(byte[] byte_arr, int start_index, int length)

    Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location)
    1. import java.io.*;    
    2. import java.lang.*;    
    3.     
    4. class Csharpcorner    
    5. {    
    6.     public static void main(String[] args)    
    7.     {    
    8.         byte[] b_arr = {67831149711411267111114110101114};    
    9.             
    10.         String s = new String(b_arr, 13);    
    11.         //Sha    
    12.             
    13.     }    
    14. }    
    In the above code, we will be generating a substring from the given byte stream.

  5. String(byte[] byte_arr, int start_index, int length, Charset char_set)

    Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location). Uses char_set for decoding.
    1. import java.io.*;    
    2. import java.lang.*;    
    3.     
    4. class Csharpcorner    
    5. {    
    6.     public static void main(String[] args)    
    7.     {    
    8.         byte[] b_arr = {67831149711411267111114110101114};    
    9.         Charset cs = Charset.defaultCharset();    
    10.         String s = new String(b_arr, 13, cs);    
    11.         //Sha    
    12.             
    13.     }    
    14. }    
    In the above code, we will be generating a substring from the given byte stream based on the given decoding technique

  6. String(byte[] byte_arr, int start_index, int length, String char_set_name)

    Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).Uses char_set_name for decoding.
    1. import java.io.*;    
    2. import java.lang.*;    
    3.     
    4. class Csharpcorner    
    5. {    
    6.     public static void main(String[] args)    
    7.     {    
    8.         byte[] b_arr = {67831149711411267111114110101114};    
    9.         Charset cs = Charset.defaultCharset();    
    10.         String s = new String(b_arr, 14, cs);    
    11.         //Shar          
    12.     }    
    13. }    
    The above is almost similar to the previous code, the only difference between the two is that he is passing the length of the substring wherein the previous we passed the end_index.

  7.  String(char[] char_arr)

    Allocates a new String from the given Character array
    1. import java.io.*;    
    2. import java.lang.*;    
    3.     
    4. class Csharpcorner    
    5. {    
    6.     public static void main(String[] args)    
    7.     {    
    8.         char b_arr[]= {'C','S','h','a','r','p','C','o','r','n','e','r'};  
    9.         String s = new String(b_arr);    
    10.         //CSharpCorner          
    11.     }    
    12. }    
    In the above code, we are converting the given character array into a String named "s".

  8. String(char[] char_array, int start_index, int count)

    Allocates a String from a given character array but choose count characters from the start_index.
    1. import java.io.*;    
    2. import java.lang.*;    
    3.     
    4. class Csharpcorner    
    5. {    
    6.     public static void main(String[] args)    
    7.     {    
    8.         char b_arr[]= {'C','S','h','a','r','p','C','o','r','n','e','r'};  
    9.         String s = new String(b_arr, 13);    
    10.         //Sha         
    11.     }    
    12. }    
    In the above code, we are generating a String from the given character stream starting from a given index and of the given length.

  9. String(int[] uni_code_points, int offset, int count)

    Allocates a String from a uni_code_array but choose count characters from the start_index.
    1. import java.io.*;    
    2. import java.lang.*;    
    3.     
    4. class Csharpcorner    
    5. {    
    6.     public static void main(String[] args)    
    7.     {    
    8.         char b_arr[]= {'C','S','h','a','r','p','C','o','r','n','e','r'};  
    9.         String s = new String(b_arr, 13);    
    10.         //CSharpCorner          
    11.     }    
    12. }    
    In the above code, we are generating a String from the given character stream with the given offset and of the given length

  10. String(StringBuffer s_buffer)

    Allocates a new string from the string in s_buffer
    1. import java.io.*;    
    2. import java.lang.*;    
    3.     
    4. class Csharpcorner    
    5. {    
    6.     public static void main(String[] args)    
    7.     {    
    8.         StringBuffer s_buffer = new StringBuffer("CSharpCorner");  
    9.     String s = new String(s_buffer);  
    10.         //CSharpCorner          
    11.     }    
    12. }    
    In the above code, we are generating a String using the StringBuffer class constructor.

  11. String(StringBuilder s_builder)

    Allocates a new string from the string in s_builder
    1. import java.io.*;    
    2. import java.lang.*;    
    3.     
    4. class Csharpcorner    
    5. {    
    6.     public static void main(String[] args)    
    7.     {    
    8.         StringBuilder s_buffer = new StringBuilder("CSharpCorner");  
    9.     String s = new String(s_buffer);  
    10.         //CSharpCorner          
    11.     }    
    12. }    
    In the above code, we are generating a String using the StringBuilder class constructor.

Java String Methods

 

1.  String.lengh()

 
Syntax
 
int length()
 
Returns the number of characters in the String 
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.         
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner          
  11.         int len = s.length();  
  12.     }    
  13. }    
In the above, we will get the answer as 12 i.e. the number of characters present in the String s.
 

2. String.charAt()

 
Syntax
 
Char charAt(int i)
 
Returns the character at the ith index
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.         
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner          
  11.         Char len = s.charAt(3);  
  12.     }    
  13. }    
In the above code, the output will be 'a' i.e. s[3]

 
3. String.substring() 

 
Syntax
 
1. String substring(int i)
 
Return the substring from the ith index character to end
 
2.  String substring(int i. int  j )
 
Returns the substring from ith to j-1 index 
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner          
  11.         Char sub = s.substring(3);  
  12.         Char sub1 = s.substring(3,5);  
  13.     }    
  14. }     
In the above code, we will get the output as 'arpCorner' and the second output as 'arp'.

 
4. String.concat()

 
Syntax
 
String concat(String str) 
 
Concatenates specified string to the end of this string
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner         
  11.         String sub = ".com";  
  12.         String ans = s.concat(sub);  
  13.     }    
  14. }    
In the above code, we concatenate String s with String sub to result out "CSharpCorner.com"
 

5. String.indexOf()

 
1. int indexOf(String s)
 
Returns the index within the starting of the first occurrence of the specified string.
 
2. int indexOf(String s, int i)
 
Returns the index within the starting of the first occurrence of the specified string, starting at the specified index
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner         
  11.         int out = s.indexOf("C");  
  12.         int out1 = s.indexOf('C',2);  
  13.     }    
  14. }    
In the above code, the output in the first case will be 1 and in the second case the output will be 8.
 

6. String.lastIndexOf()

 
Syntax
 
int lastIndexOf(String s)
 
Returns the index within the string of the last occurrence of the specified string
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner         
  11.         int out = s.lastIndexOf("C");  
  12.     }    
  13. }    
In the above code, the output will be 8
 

7. String.equals()

 
Syntax
 
boolean equals( Object otherObj)
 
Compares the string to the specified object
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner         
  11.         boolean out = s.equals("CSharpcorner");  
  12.         boolean out1 = s.eqauls("csharpcorner");  
  13.     }    
  14. }    
In the above code, the first output will be true as the ASCII code of both the Strings matches, on the other hand, in the second case the output is false, and not every ASCII code matches between the two strings
 

8. String.equalsIgnoreCase()

 
Syntax
 
boolean equalsignoreCase(String anotherstring)
 
 compares string to another string, ignoring case considerations
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner         
  11.         boolean out = s.equals("CSharpcorner");  
  12.         boolean out = s.eqauls("csharpcorner");  
  13.     }    
  14. }    
In the above code, both the outputs will be true as this method does not take into consideration the case. 
 

9. String.compareTo()

 
Syntax 
 
int compareTo(String anotherstring)
 
compares two strings lexicographically
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner         
  11.         int out = s.compareTo("Corner");  
  12.     }    
  13. }    
In the above code, the answer will be -2 as the difference between the two Strings is -2
 

10. String.compareToIgnoreCase()

Syntax
 
int  compareToIgnoreCase(String anotherString)
 
compares two strings lexicographically, ignoring case considerations.
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner         
  11.         boolean out = s.compareToIgnoreCase("Corner");  
  12.     }    
  13. }    
In the above code, the answer will be 4 as the difference between the two Strings after ignoring the case factor is 4
 

11. String.toLowerCase()

 
Syntax
 
String toLowerCase()
 
converts all the characters in the String to lower case.
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner         
  11.         String out = s.toLowerCase();  
  12.         System.out.print(out);  
  13.     }    
  14. }    
 In the above code, the whole of the String will be converted to lowercase
 

12. String.toUpperCase()

 
Syntax
 
String toUpperCase()
 
converts all the characters in the String to upper case.
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner         
  11.         String out = s.toUpperCase();  
  12.         System.out.print(out);  
  13.     }    
  14. }     
In the above code, the whole of the String will be converted to uppercase
 

13. String.trim()

 
Syntax
 
String trim()
 
Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String(" C Sharp Corner ");  
  10.         // C Sharp Corner         
  11.         String out = s.trim();  
  12.         System.out.print(out);  
  13.     }    
  14. }    
 In the above code, all the leading and trailing whitespaces will be trimmed
 

14. String.replace()

 
Syntax
 
String replace (char oldChar, char newChar)
 
Returns new String by replacing all occurrences of oldChar with newChar
  1. import java.io.*;    
  2. import java.lang.*;    
  3.     
  4. class Csharpcorner    
  5. {    
  6.     public static void main(String[] args)    
  7.     {    
  8.          
  9.         String s = new String("CSharpCorner");  
  10.         //CSharpCorner         
  11.         String out = s.replace('C''A');  
  12.         System.out.print(out);  
  13.     }    
  14. }    
In the above code, all the occurrences of 'C' will be replaced with 'A'.
 

Conclusion

 
In the article,  we learned about Java String, features and shortcomings of Java String, StringBuffer Class, Java String Constructors, Java Strings methods, and their Java Implementation.
 
Next tutorial in this series>> Java Scanner