Java Strings

String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable object which means it is constant and cannot be changed. String is a class which is available in java.lang package.

Creating a String

There are two ways to create a String in Java

  1. String literal
  2. Using new keyword
String literal

In java string object can be created using string literal using double quotes.


    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 the 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";//It doesn't create a 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 that is why it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create a new object but will return the reference to the same instance.

Using new keyword

Strings object can be created using new keyword in java, once string has been create with the help of new keyword then string object will be saved in heap memory area.


    String s=new String("Welcome");
  

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 a heap (non-pool).

Immutable String in 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.

Java String Methods

Here are the list of the methods available in the Java String class. These methods are explained in the separate tutorials with the help of examples. Links to the tutorials are provided below:

char charAt(int index): It returns the character at the specified index. Specified index value should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if index<0||>= length of String.

boolean equals(Object obj): Compares the string with the specified string and returns true if both matches else false.

boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the case while comparing strings. It does a case insensitive comparison.

int compareTo(String string): This method compares the two strings based on the Unicode value of each character in the strings.

int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the case during comparison.

boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the specified offset index) is having the specified prefix or not.

boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes then it returns true else false.

boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.

int hashCode(): It returns the hash code of the string.

int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the string.

int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in the string from the specified fromIndex.

int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.

int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts search from fromIndex.

int indexOf(String str): This method returns the index of first occurrence of specified substring str.

int lastindexOf(String str): Returns the index of last occurrence of string str.

String substring(int beginIndex): It returns the substring of the string. The substring starts with the character at the specified index.

String substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.

String concat(String str): Concatenates the specified string “str” at the end of the string.

String replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar with the newChar.

boolean contains(CharSequence s): It checks whether the string contains the specified sequence of char values. If yes then it returns true else false. It throws NullPointerException of ‘s’ is null.

String toUpperCase(Locale locale): Converts the string to upper case string using the rules defined by specified locale.

String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).

public String intern(): This method searches the specified string in the memory pool and if it is found then it returns the reference of it, else it allocates the memory space to the specified string and assign the reference to it.

public boolean isEmpty(): This method returns true if the given string has 0 length. If the length of the specified Java String is non-zero then it returns false.

public static String join(): This method joins the given strings using the specified delimiter and returns the concatenated Java String

String replaceFirst(String regex, String replacement): It replaces the first occurrence of substring that fits the given regular expression “regex” with the specified replacement string.

String replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular expression regex with the replacement string.

String[] split(String regex, int limit): It splits the string and returns the array of substrings that matches the given regular expression. limit is a result threshold here.

String[] split(String regex): Same as split(String regex, int limit) method however it does not have any threshold limit.

String toLowerCase(Locale locale): It converts the string to lower case string using the rules defined by given locale.

public static String format(): This method returns a formatted java String

String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()).

String trim(): Returns the substring after omitting leading and trailing white spaces from the original string.

char[] toCharArray(): Converts the string to a character array.

static String copyValueOf(char[] data, int offset, int count): Same as above method with two extra arguments – initial offset of subarray and length of subarray.

void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): It copies the characters of src array to the dest array. Only the specified range is being copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).

static String valueOf(): This method returns a string representation of passed arguments such as int, long, float, double, char and char array.

boolean contentEquals(StringBuffer sb): It compares the string to the specified string buffer.

boolean regionMatches(int srcoffset, String dest, int destoffset, int len): It compares the substring of input to the substring of specified string.

boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len): Another variation of regionMatches method with the extra boolean argument to specify whether the comparison is case sensitive or case insensitive.

byte[] getBytes(String charsetName): It converts the String into sequence of bytes using the specified charset encoding and returns the array of resulted bytes.

byte[] getBytes(): This method is similar to the above method it just uses the default charset encoding for converting the string into sequence of bytes.

int length(): It returns the length of a String.

boolean matches(String regex):It checks whether the String is matching with the specified regular expression regex.

int codePointAt(int index): It is similar to the charAt method however it returns the Unicode code point value of specified index rather than the character itself.

Java Example for Practice on Strings

Java String length(): The Java String length() method tells the length of the string. It returns count of total number of characters present in the String. For example:


    public class Example{
      public static void main(String args[]{ 
      String s1="hello"; 
      String s2="whatsup"; 
      System.out.println("string length is: "+s1.length());  
      System.out.println("string length is: "+s2.length()); 
      }}
  

Java String compareTo(): The Java String compareTo() method compares the given string with current string.

  1. if s1 > s2, it returns a positive number
  2. if s1 < s2, it returns a negative number
  3. if s1 == s2, it returns 0

    public class CompareToExample{ 
      public static void main(String args[]){ 
      String s1="hello";
      String s2="hello"; 
      String s3="hemlo"; 
      String s4="flag";
      System.out.println(s1.compareTo(s2)); // 0 because both are equal
      System.out.println(s1.compareTo(s3)); //-1 because "l" is only one time lower than "m" 
      System.out.println(s1.compareTo(s4)); // 2 because "h" is 2 times greater than "f"
      }}
  

Java String concat() : The Java String concat() method combines a specific string at the end of another string and ultimately returns a combined string. It is like appending another string. For example:


    public class ConcatExample{
      public static void main(String args[]){
      String s1="hello";
      s1=s1.concat("how are you");
      System.out.println(s1);
      }}
  

Java String IsEmpty() : This method checks whether the String contains anything or not. If the java String is Empty, it returns true else false. For example:


    public class IsEmptyExample{ 
      public static void main(String args[]){ 
      String s1=""; 
      String s2="hello"; 
      System.out.println(s1.isEmpty());      // true
      System.out.println(s2.isEmpty());      // false
      }}
  

Java String Trim() : The java string trim() method removes the leading and trailing spaces, for example:


    public class StringTrimExample{  
      public static void main(String args[]){  
      String s1="  hello   ";  
      System.out.println(s1+"how are you");        // without trim()  
      System.out.println(s1.trim()+"how are you"); // with trim()  
      }} 
  

Java String toLowerCase() : The java string toLowerCase() method converts all the characters of the String to lower case. For example:


    public class StringLowerExample{
      public static void main(String args[]){
      String s1="HELLO HOW Are You?”;
      String s1lower=s1.toLowerCase();
      System.out.println(s1lower);}
      }
  

Java String toUpper() : The Java String toUpperCase() method converts all the characters of the String to upper case. For example:


    public class StringUpperExample{  
      public static void main(String args[]){  
      String s1="hello how are you";  
      String s1upper=s1.toUpperCase();  
      System.out.println(s1upper);  
      }}
  

Java String ValueOf(): This method converts different types of values into string.Using this method, you can convert int to string, long to string, Boolean to string, character to string, float to string, double to string, object to string and char array to string. The signature or syntax of string valueOf() method is given below:

  1. public static String valueOf(boolean b)
  2. public static String valueOf(char c)
  3. public static String valueOf(char[] c)
  4. public static String valueOf(int i)
  5. public static String valueOf(long l)
  6. public static String valueOf(float f)
  7. public static String valueOf(double d)
  8. public static String valueOf(Object o)

    public class StringValueOfExample{
      public static void main(String args[]){
      int value=20; 
      String s1=String.valueOf(value); 
      System.out.println(s1+17);       //concatenating string with 10 
      }}
  

Java String replace(): The Java String replace() method returns a string, replacing all the old characters or CharSequence to new characters. There are 2 ways to replace methods in a Java String.


    public class ReplaceExample1{
      public static void main(String args[]){ 
      String s1="hello how are you"; 
      String replaceString=s1.replace('h','t'); 
      System.out.println(replaceString); }}
  

Java String contains() : The java string contains() method searches the sequence of characters in the string. If the sequences of characters are found, then it returns true otherwise returns false. For example:


    class ContainsExample{ 
      public static void main(String args[]){ 
      String name=" hello how are you doing"; 
      System.out.println(name.contains("how are you"));  // returns true
      System.out.println(name.contains("hello"));        // returns true  
      System.out.println(name.contains("fine"));         // returns false  
      }}                      
  

Java String equals() : The Java String equals() method compares the two given strings on the basis of content of the string i.e Java String representation. If all the characters are matched, it returns true else it will return false. For example:


    public class EqualsExample{ 
      public static void main(String args[]){ 
      String s1="hello"; 
      String s2="hello"; 
      String s3="hi";
      System.out.println(s1.equalsIgnoreCase(s2));   // returns true
      System.out.println(s1.equalsIgnoreCase(s3));   // returns false
      }
      }                   
  

Java String equalsIgnoreCase(): This method compares two string on the basis of content but it does not check the case like equals() method. In this method, if the characters match, it returns true else false. For example:


    public class EqualsIgnoreCaseExample{ 
      public static void main(String args[]){ 
      String s1="hello"; 
      String s2="HELLO"; 
      String s3="hi";
      System.out.println(s1.equalsIgnoreCase(s2));   // returns true
      System.out.println(s1.equalsIgnoreCase(s3));   // returns false
      }}