๐ Strings in Java
In Java, a String is a sequence of characters. It is a widely used class for manipulating text. Strings are immutable, meaning once a string is created, its value cannot be changed.
๐ง String Characteristics
Immutable
- Once a string object is created, its value cannot be modified. Any operation on a string creates a new string object.
String Pool
- Java maintains a pool of strings to optimize memory usage. If the same string is created multiple times, the JVM reuses the string from the pool instead of creating a new one.
String Length
- The length of a string can be obtained using the
.length()
method.
- The length of a string can be obtained using the
๐น Creating Strings in Java
Using String Literals
- When you use a string literal, Java automatically adds it to the string pool.
String str = "Hello, Java!";
2. **Using the `new` Keyword**
* You can create a string explicitly using the `new` keyword, which will create a new object in memory.
```java
String str2 = new String("Hello, Java!");
๐งช Example: String Methods
public class StringsExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
// Concatenation
String result = str1 + " " + str2;
System.out.println("Concatenation: " + result);
// Length
System.out.println("Length of str1: " + str1.length());
// Convert to Uppercase
System.out.println("Uppercase: " + str1.toUpperCase());
// Check if the string contains a substring
System.out.println("Contains 'Java': " + result.contains("Java"));
}
}
๐ง Common String Methods
- .length() - Returns the length of the string.
- .toUpperCase() - Converts the string to uppercase.
- .toLowerCase() - Converts the string to lowercase.
- .substring() - Extracts a portion of the string.
- .equals() - Compares two strings for equality.
- .charAt() - Returns the character at a specified index.