Introduction to String - The Coding Shala
Home >> Data Structures >> Introduction to String
Introduction to String
A String is a collection of Unicode characters and similar to the arrays. We can perform almost all the operations on the string that we used in an array.
Below is some function that we use frequently with Strings.
The String has its own compare function, unlike the == operator. We can compare two strings in the following ways:
- we can use == operator, like string1 == string2.
- we can use equals() method. like string1.equals(string).
- we can use compareTo() method. For example string1.compareTo(string2).
The Java String compareTo() method is used for comparing two string lexicographically. If both the strings are the same then this method returns 0 else it returns a positive or negative value. It returns a positive value if the first string is lexicographically greater than the second string else returns negative.
The following example explains the compare function:
In Java, Strings are immutable which means we can't change the content of the string once it's initialized.
The following example explains the basic operation on Strings:
We know in Java, Strings are immutable so if we want to work with strings either we can convert string to char Array or can use another data structure like StringBuilder. The following example explains it:
Other Posts You May Like