Strings play a vital role in Java programming and are widely used across various applications. This blog provides more information about strings, including ways to declare strings, how memory is allocated for strings internally and methods used to perform different operations on them with examples.
What is Java Strings?
String is a fundamental and widely used data type in Java. A String is an object of class String that represents a sequence of characters which are used for storing and manipulating text. Strings are immutable, which means once a string object is created, it cannot be changed. When you make changes to the string, a new string is created instead of altering the original one. String class is present in the java.lang package.
How to create a String?
We can create a String in two ways-
1) Using String Literal or like a declaration of the Primitive data type
Example:
String name=”John”;
String name1=”John”;
In the example above, "name" and "name1" are string variables with a string literal value "John". This is a primitive type of string declaration, similar to integer, float, and long variable declarations in Java. When a String is declared in this way, the String class invokes the intern() method and the JVM checks the String Constant Pool (SCP) to see whether the string "John" exists there or not. If not, the string "John" is added to the SCP, and a reference to this string object is returned. If it is present there, the existing string reference is returned to the variable. Here, in the first example above, String name=”John” ,the string literal "John" is created in the SCP, and its reference address, 1001, is returned to the variable "name." In the second example, since the "John" string is already present in the SCP, so the same reference, 1001, is returned to the variable "name1."
You can verify this concept programmatically in Java using the following code snippet:
public class StringDemo {
public static void main(String []args) {
String name="John";
String name1="John";
System.out.println(name==name1);
}
}
The output of the above code snippet is
true
You can see that "name" and "name1" have the same reference, which returns (name==name1) as true.
2) String Object Type using the “new” keyword
Example:
String name=“John”;
String name1=new String(“John”);
In the example provided, the variables "name" and "name1" both hold the string value "John," but they are declared using different methods. The variable "name" is declared using a string literal, that's why it's created in the string constant pool (SCP). On the other hand, "name1" is declared using the "new" keyword, which creates a new object of String in the heap memory.
Let's take a closer look at the code below to better understand this distinction:
public class StringDemo {
public static void main(String []args) {
String name="John";
String name1=new String("John");
System.out.println(name==name1);
}
}
The output of the above code is
false
Even though name and name1 have the same value, they are created in different locations. Therefore, name and name1 do not access the same references, resulting (name==name1) as false.
StringBuffer and StringBuilder classes
In Java, the StringBuffer and StringBuilder classes are used to create mutable (modifiable) sequences of characters. The need for these classes arises from the fact that strings in Java are immutable. This immutability can lead to performance and memory overhead when a large number of string manipulations are performed.
Both the StringBuffer and StringBuilder classes provide similar functionality for modifying strings, but they differ in terms of synchronization and performance.
StringBuffer Class
The StringBuffer class is a part of the java.lang package in Java and is designed to be thread-safe, meaning that it can be used in multithreaded applications without the need for external synchronization. This means that multiple threads can access and modify a StringBuffer object concurrently without causing any inconsistencies or data corruption. However, this thread safety comes at the cost of some performance overhead due to the synchronization mechanisms employed to ensure thread safety.
StringBuilder Class
The StringBuilder class is a part of the java.lang package and was introduced in Java 5. It is similar to the StringBuffer class but with one key difference: it is not thread-safe. This means that it is designed for use in single-threaded environments where synchronization is not required, making it faster in such environments. However, as it is not thread-safe if it is accessed by multiple threads simultaneously, it may lead to data inconsistency. Therefore, it is important to use StringBuilder in those scenarios where concurrent access by multiple threads is not a concern.
Both StringBuilder and StringBuffer classes offer methods for appending, inserting, deleting, and modifying strings, allowing for dynamic changes to the character sequence. When performance is a concern and thread safety is not an issue, StringBuilder is generally preferred. However, if thread safety is a requirement, StringBuffer should be used.
Java String Class Methods
Some of the commonly used string methods in Java include:
charAt(int index): Returns the character at the specified index.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
System.out.println(s1.charAt(5));//String starts with index 0
}
}
Output:
m
2. compareTo(String anotherString) : Compares two strings lexicographically.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning!";
String s2="Good morning!";
String s3="Good Day!";
//compareTo returns the difference of the lengths of the strings
//s1 and s2 strings are equal so returns 0
System.out.println(s1.compareTo(s2));
//s2 is lexicographically greater than s3,so returns positive value
System.out.println(s2.compareTo(s3));
//s3 is lexicographically small than s1,so returns negative value
System.out.println(s3.compareTo(s1));
}
}
Output:
0
41
-41
3. compareToIgnoreCase(String str): Compares two strings lexicographically, ignoring case differences.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning!";
String s2="GOOD MORNING!";
//compareTo() method considers case differences
System.out.println(s1.compareTo(s2));
//compareToIgnoreCase() ignores case differences
System.out.println(s1.compareToIgnoreCase(s2));
}
}
Output:
32
0
4. concat(String str): Concatenates the specified string to the end of the current string.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning ";
String s2="Everyone";
System.out.println(s1.concat(s2));//first way
System.out.println(s1.concat("Class"));//second way
}
}
Output:
Good morning Everyone
Good morning Class
5. contains(CharSequence s): Returns true only when if the current string contains the specified sequence of char values.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning everyone.";
//method contains() returns boolean value.If string is present then it
//returns true, if not then returns false.
System.out.println(s1.contains("morning"));
System.out.println(s1.contains("class"));
}
}
Output:
true
false
6. contentEquals(CharSequence cs): Compares the string to the specified CharSequence.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning everyone!";
String s2="Good morning everyone!";
//The result is true if and only if this String represents the same
//sequence of char values as the specified sequence, false otherwise
System.out.println(s1.contentEquals(s2));//s1 and s2 are exact same
//OR System.out.println(s1.contentEquals("Good morning everyone!"));
System.out.println(s1.contentEquals("Good"));//if there are two different strings
}
}
Output:
true
false
7. endsWith(String suffix): Tests if the string ends with the specified suffix.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning everyone";
//endsWith() method returns true if the character sequence represented by the //argument is a suffix of the character sequence represented by the current object
System.out.println(s1.endsWith("everyone"));//here checking the whole string
System.out.println(s1.endsWith("one"));//here checking the character sequence
System.out.println(s1.endsWith("morning"));
}
}
Output:
true
true
false
8. equals(Object anObject): Compares the string to the specified object.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
String s2="Good morning";
String s3="GOOD MORNING";
//equals() returns true if the given object represents a String equivalent to the //current string, false otherwise
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));//s3 is in capital letter case
}
}
Output:
true
false
9. equalsIgnoreCase(String anotherString): Compares this String to another String, ignoring case considerations.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
String s2="GOOD MORNING";
//equalsIgnoreCase() returns true if the argument is not null and it represents an //equivalent String ignoring case; false otherwise
System.out.println(s1.equalsIgnoreCase(s2));
}
}
Output:
true
10. indexOf(String str): Returns the index within the string of the first occurrence of the specified substring.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
//indexOf() returns the index of the first occurrence of the character in the //character sequence represented by the current object, or -1 if the character does //not occur.
System.out.println(s1.indexOf("morning"));
System.out.println(s1.indexOf("everyone"));
}
}
Output:
5
-1
11. isEmpty(): Returns true if, and only if, length() is 0.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
String s2="";
//isEmpty() returns true if length of string is 0, otherwise false.
System.out.println(s1.isEmpty());//s1 is not empty
System.out.println(s2.isEmpty());//s2 is empty
}
}
Output:
false
true
12. length(): Returns the length of the string.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
String s2="";
System.out.println(s1.length());//counts white spaces as well
System.out.println(s2.length());//s2 is empty
}
}
Output:
12
0
13. replace(char oldChar, char newChar): Returns a string resulting from replacing all occurrences of oldChar in the current string with newChar.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
String s2="Good Day";
System.out.println(s1.replace("morning", "afternoon"));//replaces current string with //new string
System.out.println(s2.replace('o','u'));//replaces characters in the current string //with a new character
}
}
Output:
Good afternoon
Guud Day
14. startsWith(String prefix): Checks if the string starts with the specified prefix.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
String s2="Good";
System.out.println(s1.startsWith("G"));
System.out.println(s1.startsWith("g"));
System.out.println(s1.startsWith(s2));
}
}
Output:
true
false
true
15. substring(int beginIndex, int endIndex): Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
System.out.println(s1.substring(0, 1));
System.out.println(s1.substring(0, 5));//counts space here
System.out.println(s1.substring(0, 9));
}
}
Output:
G
Good
Good morn
16. split(String regex): Splits the current string around matches of the given regular expression.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
String[] s2=s1.split(" ");//splitting string s1 into two separate words by space.
//split() returns the array of strings computed by splitting the current string //around matches of the given regular expression
for(int i=0;i<s2.length;i++)
System.out.println(s2[i]);
}
}
Output:
Good
morning
17. toUpperCase(): Converts all of the characters in this String to uppercase.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
System.out.println(s1.toUpperCase());//converts all characters into Upper case.
}
}
Output:
GOOD MORNING
18. toLowerCase(): Converts all of the characters in this String to lowercase.
public class StringDemo {
public static void main(String []args) {
String s1="Good morning";
System.out.println(s1.toLowerCase());//converts all characters into Lower case.
}
}
Output:
good morning
19. trim(): Returns a string whose value is the current string, with any leading and trailing whitespace removed.
public class StringDemo {
public static void main(String []args) {
String s1=" Good morning ";
System.out.println(s1.trim());//trim whitespace (as defined above) from the beginning and end of a string.
}
}
Output:
Good morning
These are just a few methods that are used commonly, and there are many more methods available for manipulating strings in Java.
Conclusion
By utilizing the information and examples provided in this blog, Java developers can enhance their string manipulation skills and write more efficient and optimized code. Thank you for reading, and I hope this blog has been helpful in deepening your understanding of strings in Java programming.
Keep Learning!!!
Comments