String in Java
In Java, a `String` is an object that represents a sequence of characters. It belongs to the `java.lang` package, and it's widely used for handling textual data. Here are some essential methods associated with the `String` class:
1. **Creating Strings:**
- `String myString = "Hello, World!";` - Creates a string literal.
- `String anotherString = new String("Java");` - Creates a string using the `new` keyword.
2. **Length:**
- `int length = myString.length();` - Returns the length of the string.
3. **Concatenation:**
- `String combined = myString + " " + anotherString;` - Concatenates strings.
4. **Substring:**
- `String sub = myString.substring(7);` - Extracts a substring from the original string.
5. **Concatenation with Other Data Types:**
- `int number = 42;`
- `String result = "The answer is " + number;` - You can concatenate strings with other data types.
6. **Comparison:**
- `boolean isEqual = myString.equals(anotherString);` - Compares two strings for equality.
- `int compareResult = myString.compareTo(anotherString);` - Compares two strings lexicographically.
7. **Searching:**
- `int index = myString.indexOf("World");` - Finds the index of a substring.
8. **Conversion:**
- `int num = Integer.parseInt("123");` - Converts a string to an integer.
9. **Modification:**
- `String upperCase = myString.toUpperCase();` - Converts the string to uppercase.
10. **Trimming:**
- `String trimmed = myString.trim();` - Removes leading and trailing whitespaces.
These are just a few examples, and there are many more methods available in the `String` class for various operations. Strings in Java are immutable, meaning once a string is created, it cannot be changed. If you perform operations that seem to modify a string, they actually create a new string.
Comments
Post a Comment