Java Strings
String name = "Geeks" // static memory, no new memory if already present in string constant pool
String str = new String("Hello"); // not resused in string pool
Any modifications done to strings create a new string. So immutable.
String str = new String("Hello");
str.length;
str.substring(int start);
str.charAt(int index);
equals(Object obj);
equals.equalsIgnoreCase(String str);
toLowerCase();
toUpperCase();
trim();
replace(char oldChar, char newChar);
split(String regex);
contains(CharSequence c);
StringBuffer (Synchronized)
Mutable in nature, thread safe
StringBuffer demoString = new StringBuffer("GeeksforGeeks");
demoString.append(" World");
System.out.println(sb);
StringBuilder (Unsynchronized)
Mutable in nature, non thread safe
StringBuilder demoString = new StringBuilder();
demoString.append("GFG");
System.out.println(demoString);
When changed, new object of type String is created, so string is immutable
String s = "Sachin";
s.concat("Tendulkar"); // does not work
s = s.concat("Tendulkar"); // works
When ever string literal is created, it creates a new entry in constant string pool in heap, each variable in stack with the same value point to the same value in constant string pool. New creates a new memory location for the variable
String Concatenation
String s = "Hello".concat(" World");
String Interning
String s1 = new String("abc");
String s2 = s1.intern();
String s3 = "abc";
System.out.println(s2 == s3);
String Formatting
String s = "apple,banana,orange";
String[] fruits = s.split(",");
String Formatting
String name = "madam";
int age = 30;
String formatted = String.format("Name: %s, Age: %d");
System.out.println(formatted);
Advanced String Operations
char chars[] = "hello".toCharArray();
String s = "madam";
boolean s = s.equals(new StringBuilder(s).reverse().toString());