Within the Java programming language, the String class serves as a container for characters arranged in a sequence. This class is a crucial component utilized widely for the storage and manipulation of textual information. It offers a variety of predefined methods that enable developers to perform operations on strings such as extracting substrings, concatenating text segments, altering formatting, comparing texts for equality, and substituting one term with another.
Java String Class Methods
The class java.lang.String offers a variety of helpful functions for manipulating sequences of character values.
| Method | Description |
|---|---|
| char charAt(int index) | It returns char value for the particular index |
| int length() | It returns string length |
| static String format(String format, Object... args) | It returns a formatted string. |
| static String format(Locale l, String format, Object... args) | It returns formatted string with given locale. |
| String substring(int beginIndex) | It returns substring for given begin index. |
| String substring(int beginIndex, int endIndex) | It returns substring for given begin index and end index. |
| boolean contains(CharSequence s) | It returns true or false after matching the sequence of char value. |
| static String join(CharSequence delimiter, CharSequence... elements) | It returns a joined string. |
| static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) | It returns a joined string. |
| boolean equals(Object another) | It checks the equality of string with the given object. |
| boolean isEmpty() | It checks if string is empty. |
| String concat(String str) | It concatenates the specified string. |
| String replace(char old, char new) | It replaces all occurrences of the specified char value. |
| String replace(CharSequence old, CharSequence new) | It replaces all occurrences of the specified CharSequence. |
| static String equalsIgnoreCase(String another) | It compares another string. It doesn't check case. |
| String[] split(String regex) | It returns a split string-matching regex. |
| String[] split(String regex, int limit) | It returns a split string-matching regex and limit. |
| String intern() | It returns an interned string. |
| int indexOf(int ch) | It returns the specified char value index. |
| int indexOf(int ch, int fromIndex) | It returns the specified char value index starting with given index. |
| int indexOf(String substring) | It returns the specified substring index. |
| int indexOf(String substring, int fromIndex) | It returns the specified substring index starting with given index. |
| String toLowerCase() | It returns a string in lowercase. |
| String toLowerCase(Locale l) | It returns a string in lowercase using specified locale. |
| String toUpperCase() | It returns a string in uppercase. |
| String toUpperCase(Locale l) | It returns a string in uppercase using specified locale. |
| String trim() | It removes beginning and ending spaces of this string. |
| static String valueOf(int value) | It converts given type into string. It is an overloaded method. |
Java String Methods Example
Java String.toUpperCase and String.toLowerCase Method
The method String.toUpperCase transforms the text to uppercase, while String.toLowerCase changes it to lowercase.
Example
public class Main {
public static void main(String ar[]) {
String s = "Computer";
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s);
}
}
Output:
COMPUTER
computer
Computer
Java String.trim Method
This method removes any leading and trailing white spaces from the String.
Example
public class Main {
public static void main(String ar[]) {
String s = " computer ";
System.out.println(s);
System.out.println(s.trim());
}
}
Output:
computer
computer
Java String.startsWith and String.endsWith Method
The method String.startsWith validates if the initial characters of a String match the specified input, while String.endsWith confirms if the final characters of a String correspond with the provided criteria.
Example
public class Main {
public static void main(String ar[]) {
String s = "Computer";
System.out.println(s.startsWith("C"));// true
System.out.println(s.endsWith("r"));// true
}
}
Output:
true
true
Java String.charAt Method
The method String.charAt retrieves and returns the character located at a specific index within a string.
Example
public class Main {
public static void main(String ar[]) {
String s = "Laptop";
System.out.println(s.charAt(2));// S
System.out.println(s.charAt(1));// h
}
}
Output:
Java String.length Method
The method String.length provides the length of a specified String.
Example
public class Main {
public static void main(String ar[]) {
String s = "Lamborghini";
System.out.println(s.length());
}
}
Output:
Java String.intern Method
The class String privately manages a collection of strings, which starts empty.
Upon calling the intern method, if the pool includes a String that matches the current String object based on the equals(Object) method, the String from the pool will be returned. If there is no matching String in the pool, the current String object will be added to the pool, and a reference to it will be returned.
Example
public class Main {
public static void main(String ar[]) {
String s = new String("Apple");
String s2 = s.intern();
System.out.println(s2);
}
}
Output:
Java String.valueOf Method
The String.valueOf function converts various data types like integer, long, floating-point, double, boolean, character, and character array into a string representation.
Example
public class Main {
public static void main(String ar[]) {
int a = 10;
String s = String.valueOf(a);
System.out.println(s + 10);
}
}
Output:
Java String.replace Method
The method String.replace is used to substitute all instances of a specific set of characters with another set of characters within a string.
Example
public class Main {
public static void main(String ar[]) {
String s1 = "Java is a programming language. Java is a platform. Java is an Island.";
String replaceString = s1.replace("Java", "Kava");// replaces all occurrences of "Java" to "Kava"
System.out.println(replaceString);
}
}
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
Advantages
- Built-in and Easy to Use: There is no need to write custom logic to handle common string tasks. Java provides many ready-made methods such as length, substring, toLowerCase and many more.
- Improve Readability of code: Code becomes cleaner and easier to read and understand.
- Safe and Reliable: String methods reduce the chances of errors as these are tested and stable.
- Immutability Can Waste Memory: A new object is created every time we change a string using methods such as replace while doing many changes this is not suitable. Hence, we can use StringBuilder class for the performance purposes.
- Can Be Slower in Heavy Operations: String methods are slow as compare to alternative methods such as StringBuilder for tasks such as looping over large text or constantly changing in the string method.
- Null Pointer Risk: We always have to check for null before using string methods. Using methods on a null string throws NullPointerException.
Disadvantages
Conclusion
The String class is beneficial for manipulating text effortlessly by offering a variety of handy functions like length, toLowerCase, replace, and more. These functions aid in simplifying our code, enhancing readability, and optimizing our productivity.
In Java, strings are immutable, indicating that they are unable to be altered once they are created. This characteristic can lead to memory wastage when strings are frequently modified. To optimize performance in scenarios where string modifications are frequent, StringBuilder can be utilized.
It is crucial to verify the absence of a value before employing any string operations to prevent potential errors. In general, the String class stands as a vital and robust component within Java development.