Characters
- a character is a single 16-bit Unicode character, represented by the
charprimitive data type. - It can store any character from the Unicode character set (e.g., letters, digits, symbols).
char ch = 'A'; // Stores the character 'A' char unicodeChar = '\u0041'; // Unicode for 'A'
Strings
- A string is a sequence of characters.
- In Java, strings are objects of the
Stringclass (from thejava.langpackage), not primitive types. - Strings are immutable, meaning their content cannot be changed after creation.
String str = "Hello, World!";
string class
key features
-
immutability: ensures thread safety and security (e.g., in class loading or as keys in hash-based collections).
-
string pool: java maintains a pool of string literals to optimize memory. Strings created using literals (e.g.,
"Hello") are stored in the pool, while those created withnew String("Hello")are not (unless interned).String str1 = new String(); // Empty string String str2 = new String("Hello"); // String from literal char[] chars = {'H', 'i'}; String str3 = new String(chars); // String from char array -
string methods
length(): Returns the number of characters.charAt(int index): Returns the character at the specified index.substring(int beginIndex, int endIndex): Returns a substring.toUpperCase()/toLowerCase(): Converts case.indexOf(String str): Returns the index of the first occurrence ofstr.equals(Object obj)/equalsIgnoreCase(String str): Compares strings.trim(): Removes leading/trailing whitespace.replace(char oldChar, char newChar): Replaces characters.
valueO()
The String class provides valueOf() methods to convert various data types to strings. These are static methods.
int num = 42;
String strNum = String.valueOf(num); // "42"
double d = 3.14;
String strDouble = String.valueOf(d); // "3.14"
boolean b = true;
String strBool = String.valueOf(b); // "true"
char[] chars = {'H', 'i'};
String strChars = String.valueOf(chars); // "Hi"
StringBuffer Class
- The
StringBufferclass is used for mutable strings, unlike the immutableStringclass. It is thread-safe (synchronized methods), making it suitable for multi-threaded applications. - Key Features of StringBuffer hello
- Mutable: Allows in-place modification of the character sequence.
- Thread-safe: Synchronized methods ensure safe use in multi-threaded environments.
- Capacity: Internal buffer size, which grows dynamically (default initial capacity is 16).
StringBuffer sb1 = new StringBuffer(); // Empty, capacity 16
StringBuffer sb2 = new StringBuffer("Hello"); // Initialized with "Hello"
StringBuffer sb3 = new StringBuffer(50); // Empty, capacity 50
- StringBuffer Methods
append(String str): Appends data (overloaded for various types: int, double, etc.).insert(int offset, String str): Inserts data at the specified position.delete(int start, int end): Removes characters fromstarttoend-1.replace(int start, int end, String str): Replaces characters fromstarttoend-1withstr.reverse(): Reverses the character sequence.capacity(): Returns the current capacity.ensureCapacity(int minCapacity): Ensures the buffer has at least the specified capacity.toString(): Converts theStringBufferto aString.
When to Use StringBuffer
- Use
StringBufferfor string manipulation in multi-threaded environments. - For single-threaded applications, prefer
StringBuilderfor better performance (no synchronization overhead). - Example:
StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1000; i++) { sb.append(i); // Efficient for repeated modifications }
String vs. StringBuffer
| Feature | String | StringBuffer |
|---|---|---|
| Mutability | Immutable | Mutable |
| Thread-Safety | Thread-safe (immutable) | Thread-safe (synchronized) |
| Performance | Slower for modifications | Faster for modifications |
| Memory Usage | Creates new objects | Modifies in-place |
| Use Case | Fixed strings | Dynamic string manipulation |