Open-Source Internship opportunity by OpenGenus for programmers. Apply now.
Reading time: 35 minutes
A string is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In Java, strings are treated as objects of class String.
Strings are immutable objects which means they are constant and cannot be changed once it has been created.
With this article, we answer the following questions:
- How to create a string in Java?
- Does String class has a Constructor?
- How to compare Strings in Java?
- How to search a string in Java?
- How to change upper/ lower case in a String?
- How to get a Substring in Java?
- Some useful methods of Strings in Java
- What does immutablity of String in Java imply?
- Comparing String, StringBuffer and StringBuilder in Java
- When to use StringBuffer or StringBuilder instead of String in Java?
With this, you will master the basics of String in Java and will have a perfect working knowledge.
How to create a string in Java?
There are two ways to create a String in Java:
- Using string literals
- Using new keyword
1. Using string literals:
Following is the syntax for this method:
String s = “OpenGenus”;
2. Using new keyword:
Following is the syntax for this method:
String s = new String (“OpenGenus”);
Does String class has a Constructor?
Yes, String class like any other class in Java has a constructor. There are different types of constructor for String class. They are as follows:
- String() : Allocates a new String containing no characters.
Example:
String s = new String();
- String(byte[] bytes, int offset, int length, String enc): Constructs a new String by converting the specified subarray of bytes using the specified character encoding.
- String(byte[] bytes, int offset, int length): Constructs a new String by converting the specified subarray of bytes using the Java's default character encoding.
- String(byte[] bytes): Construct a new String by converting the specified array of bytes using the Java platform's default character encoding.
- String(char[] value, int offset, int count): Allocates a new String that contains characters from a subarray of the character array argument.
- String(char[] value): Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
Example:
String s = new String (['O', 'p', 'e', 'n', 'G', 'e', 'n', 'u', 's']);
- String(String value): Allocates a new string that contains the same sequence of characters as the string argument.
Example:
String s = new String ("OpenGenus");
- String(StringBuffer buffer): Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
Example:
StringBuffer sb = new StringBuffer("OpenGenus");
String s = new String (sb);
How to compare Strings in Java?
String class in Java contains several methods to compare Strings such as:
Comparison methods:
- compareTo(Object o): Compares this String to another Object.
- compareTo(String anotherString): Compares two strings lexicographically.
- compareToIgnoreCase(String str): Compares two strings lexicographically ignoring case considerations.
- equals(Object anObject): Compares this string to the specified object.
- equalsIgnoreCase(String anotherString): Compares this String to another object.
Implementation
import java.io.*;
import java.util.*;
class StringOperations
{
public static void main (String[] args)
{
Boolean out = "Java".equals("java");
System.out.println("Checking Equality of 'Java' and 'java' = "
+ out);
out = "Java".equals("Java");
System.out.println("Checking Equality of 'Java' and 'Java' = "
+ out);
out = "Java".equalsIgnoreCase("jaVa ");
System.out.println("Checking Equality of 'Java'and 'jaVa', ignoring case = "
+ out);
String s1 = "Open";
String s2 = "Genus";
System.out.println("String s1 = "+ s1 + " , " + "String s2 = " + s2);
int out1 = s1.compareTo(s2);
System.out.println("If s1 = s2 : " + out);
}
}
Output
Checking Equality of 'Java' and 'java' = false
Checking Equality of 'Java' and 'Java' = true
Checking Equality of 'Java'and 'jaVa', ignoring case = false
String s1 = Open , String s2 = Genus
If s1 = s2 : false
How to search a string in Java?
String class in Java contains several methods to search within Strings such as:
- charAt(int index): Returns the character at the specified index.
- indexOf(int ch, int fromIndex): Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
- indexOf(int ch): Returns the index within this string of the first occurrence of the specified character.
- indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
- indexOf(String str): Returns the index within this string of the first occurrence of the specified substring.
- lastIndexOf(int ch, int fromIndex): Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
- lastIndexOf(int ch): Returns the index within this string of the last occurrence of the specified character.
- lastIndexOf(String str, int fromIndex): Returns the index within this string of the last occurrence of the specified substring.
- lastIndexOf(String str): Returns the index within this string of the rightmost occurrence of the specified substring.
Implementation
import java.io.*;
import java.util.*;
class StringOperations
{
public static void main (String[] args)
{
String s= new String ("OpenGenus");
System.out.println("Given string is = " + s);
System.out.println("Character at 3rd position = "
+ s.charAt(3));
String s1 = "Java String Class";
System.out.println("String s1 = "+s1);
System.out.println("Index of Class in String s1 = " +
s1.indexOf("Class"));
System.out.println("Index of a in String s1 = " +
s1.indexOf('a',3));
System.out.println("last Index of a in String s1 = " +
s1.indexOf('a'));
}
}
Output
Given string is = OpenGenus
Character at 3rd position = n
String s1 = Java String Class
Index of Class in String s1 = 12
Index of a in String s1 = 3
last Index of a in String s1 = 1
How to change case in a String?
String class in Java contains several methods to change case of Strings such as:
- toLowerCase(): Converts all of the characters in this String to lower case.
- toUpperCase(): Converts all of the characters in this String to upper case.
Implementation
import java.io.*;
import java.util.*;
class StringOperations
{
public static void main (String[] args)
{
String word1 = "Learn and Share";
System.out.println("String word1 = "+word1);
System.out.println("Changing string word1 to lower Case = "
+ word1.toLowerCase());
String word2 = "learn AND share";
System.out.println("String word2 = "+word2);
System.out.println("Changing string word2 to UPPER Case = "
+ word2.toUpperCase());
}
}
Output
String word1 = Learn and Share
Changing string word1 to lower Case = learn and share
String word2 = learn AND share
Changing string word2 to UPPER Case = LEARN AND SHARE
How to get a Substring in Java?
String class in Java contains several methods to get substrings from Strings such as:
- substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string.
- substring(int beginIndex): Returns a new string that is a substring of this string.
Implementation
import java.io.*;
import java.util.*;
class StringOperations
{
public static void main (String[] args)
{
String s= new String ("OpenGenus");
System.out.println("Given string is = " + s);
System.out.println("Substring = " + s.substring(3));
System.out.println("Substring = " + s.substring(2,5));
}
}
Output
Given string is = OpenGenus
Substring = nGenus
Substring = enG
Some useful methods of Strings in Java
String class in Java contains several methods to operate on Strings such as:
- length(): Returns the length of this string.
- trim(): Removes white space from both ends of this string.
- concat(String str): Concatenates the specified string to the end of this string.
- endsWith(String suffix): Tests if this string ends with the specified suffix.
- hashCode(): Returns a hashcode for this string.
Implementation
import java.io.*;
import java.util.*;
class StringOperations
{
public static void main (String[] args)
{
String s1 = "Open";
String s2 = "Genus";
System.out.println("String s1 = "+ s1 + " , " + "String s2 = " + s2);
System.out.println("Length of string s1 = " + s1.length());
System.out.println("Concatenated string of Strings s1 and s2 = "
+s1.concat(s2));
System.out.println("Does string s1 ends with 'rbk' = "
+ s1.endsWith("rbk"));
String word3 = " Learn And Share ";
System.out.println("String word3 = "+word3);
System.out.println("Trim the string word3 = " + word3.trim());
String str1 = "OpenGenus";
System.out.println("String str1 = "+str1);
System.out.println("Original String str1 = " + str1);
String str2 = str1.replace('A' ,'O') ;
System.out.println("Replaced A with O in string str1 -> " + str2);
}
}
Output
String s1 = Open , String s2 = Genus
Length of string s1 = 4
Concatenated string of Strings s1 and s2 = OpenGenus
Does string s1 ends with 'rbk' = false
String word3 = Learn And Share
Trim the string word3 = Learn And Share
String str1 = OpenGenus
Original String str1 = OpenGenus
Replaced A with O in string str1 -> OpenGenus
What does immutablity of String in Java imply?
String class in Java is immutable. This means that a String object cannot be modified. The problem is that you might have modified Strings but internally, it is creating a new String object and the old object is released.
In this case, the old object is free to be deleted but we cannot do it as we have lost reference to it. It will be removed in the next garbage collection phase.
Consider this:
- We create a new String object:
String name = "Open"; // One object created
- Modifying the string
name = name + "Genus"; // New object is created
With this, we have created two string objects and this is an overhead if such modifications are done repeatedly as object creation is a slow process in Java.
The new object creation can be tested using the hashcode of the name object. We will get different hashcodes before and after the modification.
System.out.println(name.hashCode());
The solution to this is to use StringBuffer class whose objects are mutable.
Comparing String, StringBuffer and StringBuilder in Java
The main differences between String and StringBuffer are:
- String objects are immutable and StringBuffer objects are mutable
- String class overrides the equals() method so string objects can be compared directly but the StringBuffer object does not override equals() method.
- StringBuffer objects are synchronized and hence, all methods are thread safe. This comes at an overhead.
- StringBuilder objects are mutable like StringBuffer but it is not synchronized/ thread safe and hence, it is a bit faster.
When to use StringBuffer or StringBuilder instead of String?
When the string objects are modified repeatly, then a better option is to use the StringBuffer class as:
- It is reduce the number of objects created
- Due to the above point, the code will run faster
- Similarly, the garbage collection phase will be triggered less frequently and hence, less pause.
If the application is not multithreaded, then one may use StringBuilder instead of StringBuffer which will accelerate the code execution further.