Introduction:
In Java, the String
class is a part of the java.lang
package and is used to represent sequences of characters. Strings are immutable, which means their values cannot be changed once they are created. In this tutorial, we’ll explore various operations and methods available in the String
class.
1. Creating Strings:
Strings in Java can be created in multiple ways:
a. Using String Literal:
<code>String strLiteral = "Hello, World!";</code>
b. Using new
Keyword:
String strObject = new String("Hello, World!");
2. String Length:
To get the length of a string, use the length()
method:
String greeting = "Hello, Java!";
int length = greeting.length();
System.out.println("Length of the string: " + length);
3. Concatenation:
You can concatenate strings using the +
operator or the concat()
method:
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // Using +
// OR
String fullNameConcat = firstName.concat(" ").concat(lastName); // Using concat()
4. Substring:
Extracting a substring from a string using the substring()
method:
String original = "Hello, World!";
String substring = original.substring(7); // Extracts from index 7 to the end
System.out.println("Substring: " + substring);
5. String Comparison:
To compare strings, use equals()
for content comparison, and compareTo()
for lexicographic comparison:
String str1 = "Java";
String str2 = "java";
// Content comparison
boolean isEqual = str1.equals(str2);
// Lexicographic comparison
int result = str1.compareTo(str2);
6. Searching within a String:
To check if a string contains a specific substring or character, use contains()
or indexOf()
:
String sentence = "Java is fun!";
boolean containsJava = sentence.contains("Java");
int indexOfIs = sentence.indexOf("is");
7. String Manipulation:
Various methods are available for manipulating strings:
String text = " Trim me ";
String trimmed = text.trim(); // Removes leading and trailing whitespaces
String upperCase = text.toUpperCase();
String lowerCase = text.toLowerCase();
8. String Splitting:
Splitting a string into an array of substrings:
String csvData = "John,Doe,30";
String[] parts = csvData.split(",");
Conclusion:
The String
class in Java provides a rich set of methods for working with text. Understanding its methods is essential for efficient string manipulation in Java applications. Explore the official Java documentation for more details and additional methods available in the String
class: String (Java Platform SE 8).