Java String Methods with Examples

By Kiran G, 06 May,2018   0K

In this blog post we are going to discuss about Java Strings concept. In general String is a sequence of individual characters. Strings are widely used in many programming languages, but in Java, Strings are considered as objects. Java provides a java.lang.String class for creating string objects and do operations.

Java String Example - 1

public class StringDemo1 {
   public static void main(String args[]) {
      String firstString = "Java String Example.!";
      System.out.println(firstString);
   }
}

Output: Java String Example.!

Java String Example - 2

public class StringDemo2 {
 public static void main(String args[]) {
   char[] charArray = { 'J', 'a', 'v', 'a', 's', 't','r','i','n','g' };
      String firstString = new String(charArray);  
      System.out.println( firstString );
   }
}

Output: Javastring

Java String is Immutable

Java string objects are immutable and final. Once we create string class, string objects are immutable. That means, string objects are unchangeable and unmodifiable, we cannot change it’s data and state. See below example to understand the Java string immutable concept.

Java String Immutability Example

public class ImmutableStringDemo{  
   public static void main(String args[]){  
      String immutableString ="Java String";  
      immutableString.concat(" Is Immutable"); //concat() method appends the string at the end  
      System.out.println(immutableString); //will print Java String because strings are immutable  
 }  
}  
Output: Java String

Explanation: From the above example we can clearly understand that, string objects are immutable. Why because, new object is created in the memory when we concat() method to immutableString object. But the reference variable immutableString still refers to the string “Java String” not to “Java String Is Immutable”.

But if we can assign value to the reference variable explicitly to get the value “Java String Is Immutable”. See below example,

 public class ImmutableStringDemo{  
   public static void main(String args[]){  
      String immutableString ="Java String";  
      immutableString = immutableString.concat(" Is Immutable");              
      System.out.println(immutableString);  
 }  
}  

Output: Java String Is Immutable

Explanation: In the above example, string object immutableString refers to “Java String Is Immutable”. This is because of we explicitly assign the value to the reference variable immutableString.

Java StringBuffer and StringBuilder

Java String class is immutable. Whenever we want to do operations on strings, new objects will be created and consumed more resources. To overcome this issue, Java has two utility classes called StringBuffer and StringBuilder. These two classes are mutable, unlike string objects and we can use these class objects whenever we want to do more operations on strings.

StringBuffer Vs StringBuilder

Type of StringBuffer and StringBuilder objects are mutable.

We can do any number of modifications to these mutable objects.

StringBuffer is synchronized, whereas StringBuilder in non-synchronized.

StringBuffer operations are thread safe, whereas StringBuilder operations are not thread safe.

In StringBuffer two threads can’t call the methods simultaneously, whereas in StringBuilder two threads can call the methods simultaneously.

StringBuffer is less efficient and slower when compared to StringBuilder.

Java StringBuffer Example

public class BufferDemo{  
    public static void main(String[] args){  
        StringBuffer bufferTest=new StringBuffer("Java String");  
        bufferTest.append("Buffer");  
        System.out.println(bufferTest);  
    }  
}  

Output: Java StringBuffer

Java StringBuilder Example

public class BuilderDemo{  
    public static void main(String[] args){  
        StringBuilder builderTest=new StringBuilder("Java String");  
        builderTest.append("Builder");  
        System.out.println(builderTest);  
    }  
}  

Output: Java StringBuilder

List of Java String Methods

length()
concat()
compareTo()
isEmpty()
trim()
toLowerCase()
toUpper()
valueOf()
replace()
contains()
equals()
equalsIgnoreCase()
toCharArray()
getBytes()
endsWith()

Java String Methods With Examples

1) String Length : Java string length() method is used to find length of a string, that means the count of number of character in a string.

Java String length() Example

public class StringLength{
 public static void main(String args[]){ 
  String stringDemo="Java Programming"; 
  System.out.println("String Length is: "+stringDemo.length()); 
 }
}

Output: String length is: 16

2) String Concatenation : Java string concat() method is used to concatenate two strings. This concat method append string two to string one at the end.

Java String concat() Example

public class StringConcat{
 public static void main(String args[]){
 String stringText="Java String";
 stringText=stringText.concat(" Concatenation Example");
 System.out.println(stringText);
 }
}

Output: Java String Concatenation Example

3) String Compare: Java string compareTo() method is used to compare one string with other in alphabetical order. compareTo() method returns either positive number, negative number or 0.

Java String compareTo() Example

public class CompareToDemo{ 
 public static void main(String args[]){ 
 String str1="java";
 String str2="java"; 
 String str3="jeva"; 
 String str4="gova";
 System.out.println(str1.compareTo(str2)); // 0 because both are equal
 System.out.println(str1.compareTo(str3)); //-4 because "a" is 4 times lower than "e" 
 System.out.println(str1.compareTo(str4)); // 3 because "j" is 3 times greater than "g"
 }
} 

Output

:
 
0
-4
3

4) String Empty: Java string IsEmpty() method is used to check whether the string is empty or not. If the string is empty it will return true, if there is any data it will return false.

Java String IsEmpty() Example

public class IsEmptyDemo{ 
 public static void main(String args[]){ 
 String str1=""; 
 String str2="java"; 
 System.out.println(str1.isEmpty());      // true
 System.out.println(str2.isEmpty());      // false
 }
}

Output:

True
False 

5) String Trim: Java string trim() method removes the space before and after the string. It will return a string without spaces.

Java String trim() Example:

public class StringTrimDemo{  
 public static void main(String args[]){  
 String str1="  java programming   ";  
 System.out.println(str1+"is awesome");        // without trim()  
 System.out.println(str1.trim()+"is awesome"); // with trim()  
 }
}

Output:

 java programming   is awesome
java programmingis awesome

6) String to Lowercase: Java string toLowerCase() method is used to convert the all string characters in to lowercase.

Java String toLowerCase() Example:

public class StringToLowerDemo{
 public static void main(String args[]){
 String str1="JAVA PROGRAMMING";
 String stringLower=str1.toLowerCase();
 System.out.println(stringLower);
 }
}

Output: java programming

7) String to Uppercase: Java string toUpperCase() method is used to convert all the characters of string into uppercase.

Java String toUpperCase() Example:

public class StringToUpperDemo{
 public static void main(String args[]){
 String str1="java programming";
 String stringUpper=str1.toUpperCase();
 System.out.println(stringUpper);
 }
}

Output: JAVA PROGRAMMING

8) String Valueof: Java string ValueOf() method is used to convert other type of values into strings. Using this ValueOf() method we can convert, int, long, float, double, boolean, char, object and char array into string.

Java String ValueOf() Example:

public class StringValueOfDemo{
 public static void main(String args[]){
 int year=19; 
 String str1=String.valueOf(year); 
 System.out.println(str1+87);       //concatenating string with 19 
 }
}

Output: 1987

9) String Replace: Java string replace() method is used to replace existing characters to new set of characters and also we can replace a string of characters to new set of characters. The replace() method returns a string.

Java String replace() Example 1: Replacing Characters

public class StringReplaceDemo
{
 public static void main(String args[])
 { 
  String string1="java programming"; 
  String stringReplace=string1.replace('j','n'); 
  System.out.println(stringReplace); 
 }
}

Output: nava programming

Here ‘j’ replaced with ‘n’ in “java programming” and prints output as “nava programming”.

Java String replace() Example 2: Replacing String of Characters

public class ReplaceStringDemo
{ 
 public static void main(String args[])
 { 
  String string1="Java Programming is Awesome.!"; 
  String stringReplace=string1.replace("Java","Python"); 
  System.out.println(stringReplace); 
 }
}

Output: Python Programming in Awesome.!

Here replace() method replaces “Java” string in “Java Programming is Awesome.!” with “Python” and print output as “Python Programming is Awesome.!”.

10) String Contains: Java string contains() method is used to search a sequence of characters in a string. If that searched sequence is found in string it will return true, it that sequence of character not found in string it will return false.

Java String contains() Example:

public class ContainsStringDemo
{ 
 public static void main(String args[])
 { 
  String name=" java strings are immutable "; 
  System.out.println(name.contains("java"));  // returns true
  System.out.println(name.contains("java strings"));        // returns true  
  System.out.println(name.contains("programming"));         // returns false  
 }
}

Output:

True
Ture
False

11) String Equals: Java string equals() method is used to compare two given strings. If all the characters in two strings are matched (case-sensitive) then equals() method returns true, otherwise it will return false.

Java String equals() Example:

public class StringEqualsDemo
{ 
  public static void main(String args[])
  { 
  String string1="java"; 
  String string2="java"; 
  String string3="Java";
  String string4="jav";
  System.out.println(string1.equals(string2));   // returns true
  System.out.println(string1.equals(string3));   // returns false
  System.out.println(string1.equals(string4));   // returns false
  }
}

Output:

True
False
False

12) String Equals Ignore Case: Java string equalsIgnoreCase() method is used compare characters in strings but not the case like in equals() method. The equalsIgnoreCase() method check only data not the character case. If data matches in two string it will return true, or else it will return false.

Java String equalsIgnoreCase() Example:

public class StringEqualsIgnoreCaseDemo
{ 
  public static void main(String args[])
  { 
  String string1="java"; 
  String string2="Java"; 
  String string3="Jav";
  System.out.println(string1.equalsIgnoreCase(string2));   // returns true
  System.out.println(string1.equalsIgnoreCase(string3));   // returns false
  }
}

Output:

 
True
False

13) String to Char Array: Java string toCharArray() method is used when we want to convert a string into character array. The toCharArray() method initially calculates the size of the given string including spaces and then create an array with the same size of the array.

Java String toCharArray() Example:

public class StringToCharArrayDemo
{
 public static void main(String args[])
 {
  String string1="Java Programming";
  char[] chararray=string1.toCharArray();
  for(int i=0;i<chararray.length;i++)
  {
  System.out.print(chararray[i]);
  }
 }
}

Output: Java Programming

14) String Get Bytes: Java string getBytes() method is used to return the sequence of bytes of a string. The bytes will be stored in a array.

Java String getBytes() Example:

public class GetBytesDemo
{
 public static void main(String args[])
 { 
  String string1="JAVA";
  byte[] byt=string1.getBytes(); 
  for(int i=0;i<byt.length;i++)
  { 
  System.out.println(byt[i]);
  }
 }
}

15) String Ends With: Java string endsWith() method is used to check whether the string is ending with the given suffix or not. If endsWith() method found given suffix in a string it will return true or else it will return false.

Java String endsWith() Example:

public class EndsWithExample
{ 
 public static void main(String args[]) 
 {
  String s1="java programming is awesome"; 
  System.out.println(s1.endsWith("me"));       // returns true
  System.out.println(s1.endsWith("some"));     // returns true   
  System.out.println(s1.endsWith("java"));     // returns false
 }
}

Output:

True
True
False

Conclusion

Now we discussed on Java strings, Java string immutability, stringbuffer and stringbuilder, their differences and examples, list of java string methods, and java string methods with examples. We hope that you understood the concept clearly, if you have a question, please leave your comment in the below comment section. We will get back to you as soon as possible.

Further Reading on Core Java

1. Java Lambda Expression

2. Java8 Streams Operations

3. Java 8 Parallel Steams

4. Java9 Modularity Features

5. Java8 Datetime Conversions

If You Appreciate What We Do Here On Devglan, You Should Consider:

References

Java String

Java String Methods