Strings in Java
In Java, the String class represents immutable sequences of characters. The JDK provieds a rich set of APIs—predefined classes and methods—for common operations.
Creating String Objects
- Literal assignment:
String name = "AWei"; - Empty string via constructor:
String s1 = new String(); - From another string:
String s2 = new String("Like"); - From a byte array:
byte[] data = {97, 98, 99, 100};<br></br> String s4 = new String(data); - From a char array:
char[] letters = {'a', 'b', 'c'};<br></br> String s3 = new String(letters);
String Comparison
Using == compares object references, not content. For value comparison, use:
String a = "abc";
String b = new String("abc");
boolean eq1 = a.equals(b); // true
boolean eq2 = a.equalsIgnoreCase("ABC"); // true (case-insensitive)
Always prefer equals() or equalsIgnoreCase() for content checks.
StringBuilder
StringBuilder is a mutable sequence of characters, ideal for frequent modifications.
Basic Usage
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder("initial");
sb.append(42)
.append(true)
.reverse();
int len = sb.length();
String result = sb.toString(); // convert back to String
Chaining (Fluent Interface)
Methods like append() return the StringBuilder instance, enabling method chaining:
String reversed = new StringBuilder()
.append(input)
.reverse()
.toString();
StringJoiner
StringJoiner constructs sequences of strings separated by a deilmiter, with optional prefix and suffix.
Constructors
StringJoiner sj1 = new StringJoiner("---"); // delimiter only
StringJoiner sj2 = new StringJoiner(",", "[", "]"); // delimiter, prefix, suffix
Methods
sj2.add("apple").add("banana");
int count = sj2.length(); // total character count
String output = sj2.toString(); // e.g., "[apple,banana]"
ArrayList
ArrayList is a resizable array implementation of the List interface.
Declaration and Initialization
ArrayList<String> list = new ArrayList<>();
When printed, it displays contents enclosed in square brackets (e.g., [item1, item2]).
Common Operations
list.add("newItem"); // add element
list.remove("oldItem"); // remove by value
list.remove(0); // remove by index (returns removed element)
list.set(1, "updated"); // replace element at index
String val = list.get(2); // retrieve element
int size = list.size(); // number of elements
Primitive Wrappers
Use wrapper classes when working with collections:
int→Integerchar→Character- Other primitives: capitalize first letter (e.g.,
double→Double)