Java String Handling
Java provides extensive support for handling strings, which are sequences of characters. Here's a
detailed breakdown of the mentioned topics:
1. String Constructors
The String class in Java offers several constructors for creating and initializing strings:
- Default Constructor:
Creates an empty string:
String s = new String(); // ""
- Using Another String:
Initializes a new string with the value of another string:
String s = new String("Hello");
- Using Character Array:
Converts a character array into a string:
char[] chars = {'J', 'a', 'v', 'a'};
String s = new String(chars); // "Java"
- Using Subset of a Character Array:
Creates a string from a specific portion of a character array:
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String s = new String(chars, 1, 3); // "ell"
- Using Byte Array:
Converts a byte array into a string, assuming the default character encoding:
byte[] bytes = {65, 66, 67};
String s = new String(bytes); // "ABC"
2. Special String Operations
Java provides several operations that can be performed on strings:
- Concatenation:
Combines two strings using the + operator or the concat() method:
String s1 = "Hello";
String s2 = "World";
String result = s1 + " " + s2; // "Hello World"
String result2 = s1.concat(" ").concat(s2); // "Hello World"
- Substring:
Extracts a part of a string:
String s = "Programming";
String sub = s.substring(0, 4); // "Prog"
- Length:
Returns the number of characters in the string:
int len = s.length(); // 11
- Case Conversion:
Converts to uppercase or lowercase:
String lower = "Hello".toLowerCase(); // "hello"
String upper = "hello".toUpperCase(); // "HELLO"
- Trimming:
Removes leading and trailing whitespace:
String s = " Java ";
String trimmed = s.trim(); // "Java"
3. Character Extraction
Methods for extracting characters or groups of characters from a string:
- charAt():
Retrieves the character at a specific index:
String s = "Hello";
char ch = s.charAt(1); // 'e'
- getChars():
Copies characters into an array:
char[] chars = new char[5];
s.getChars(0, 5, chars, 0); // chars = {'H', 'e', 'l', 'l', 'o'}
- toCharArray():
Converts the entire string into a character array:
char[] chars = s.toCharArray(); // {'H', 'e', 'l', 'l', 'o'}
4. String Comparisons
Strings can be compared using various methods:
- equals():
Checks if two strings are identical (case-sensitive):
String s1 = "Hello";
String s2 = "Hello";
boolean isEqual = s1.equals(s2); // true
- equalsIgnoreCase():
Checks equality, ignoring case:
boolean isEqual = s1.equalsIgnoreCase("hello"); // true
- compareTo():
Compares strings lexicographically:
int result = s1.compareTo("World"); // negative value since "Hello" < "World"
- startsWith() and endsWith():
Checks if a string starts or ends with a specific substring:
boolean starts = s1.startsWith("He"); // true
boolean ends = s1.endsWith("lo"); // true
5. Modifying a String
Since strings in Java are immutable, modification operations create a new string:
- Replace Characters or Substrings:
String s = "Java";
String replaced = s.replace('a', 'o'); // "Jovo"
String replacedStr = s.replace("Java", "Python"); // "Python"
- Concatenation:
Adds a string to another string:
String s = "Hello";
s = s.concat(" World"); // "Hello World"
6. StringBuffer
Unlike String, StringBuffer is mutable, meaning its content can be modified. It is thread-safe but
slower compared to StringBuilder.
Common Methods of StringBuffer:
- Append:
Adds data to the end of the string:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // "Hello World"
- Insert:
Inserts data at a specific position:
sb.insert(6, "Java "); // "Hello Java World"
- Replace:
Replaces part of the string:
sb.replace(6, 10, "Amazing"); // "Hello Amazing World"
- Delete:
Removes characters from the string:
sb.delete(6, 13); // "Hello World"
- Reverse:
Reverses the string:
sb.reverse(); // "dlroW olleH"
- Capacity Management:
StringBuffer has an initial capacity, which grows as needed:
StringBuffer sb = new StringBuffer();
sb.ensureCapacity(50); // Ensures the capacity is at least 50
Key Differences Between String and StringBuffer
| Feature | String (Immutable) | StringBuffer (Mutable) |
|--------------------|-----------------------|----------------------------|
| Modification | Creates a new object | Modifies the same object |
| Thread-Safety | Not thread-safe | Thread-safe |
| Performance | Faster for reads | Slower due to synchronization |
By mastering these topics, you'll be well-equipped to handle Java's powerful string manipulation
capabilities effectively.