Strings

3 minute read

String Interning

When we use double quotes to create a string, it first looks for the string with the same value in the String Pool. If found it just returns the reference

JVM does so, for conserving memory (FLYWAY DESIGN PATTERN).

// Both the String one & two variables are created on the Stack but reference to the same String on heap
String one = "Hello";
String two = "Hello";// JVM uses the String Pool
        
String three = new String("Hello");// Forcing to create a new String on Heap
String three = "Hello".intern();//intern used explicitly
String Mutability

All Strings in Java are Immutable.Strings are made to be immutable as a consequence of Memory Pool concept.

One string is shared among many objects (due to the String pool concept) due to which string.concat() creates a new object everytime.

Thus, the use of StringBuilder is preferred to create strings.

  • StringBuilder is NON-SYNCHRONIZED thus more efficient
  • StringBuffer is SYNCHRONIZED (THREAD SAFE) means two threads can call the methods of the object simultaneously.
    • Comparatively less efficient than String Builder
String s = new StringBuilder()
                .append("John").append(" H").append(" Doe")
                .toString();
String.equals and equalsIgnoreCase

Sting.equals() method checks for string equality while == compares the references

String x = "";
String y = "";
//Here String x and y are two different String objects lying in the "Heap" pointing to the same reference.
if (x == y) {
    System.out.println("x and y are referring to a same String");
}

String Methods

length(), compare() & equals()
//Method in String, Field in Arrays;
str.length();

str1.equals(str2);//For Equality, DO NOT USE == (will compare objects)
        
str1.compareTo(str2);
// negative if str is "lexicographically" less than str2
// positive if str is "lexicographically" greater than str2
// ZERO is both strings are equal
isBlank()
System.out.println("".isBlank());//True
System.out.println(" ".isBlank());//True -> Returns true if the string is empty or contains only white space
split()

Splitting a String, from comma separated values to individual tokens

//Cut the Strings from spaces into a words
String[] words = strList.split(",");
trim() and strip
String s = " Malgudi Days   ";

System.out.println(s.trim());//Trimmed blank spaces with all leading and trailing space removed

System.out.println(s.strip());//Strip is Unicode Aware
System.out.println(s.stripLeading());
System.out.println(s.stripTrailing());
contains
String sentence = "Hello, world!";
// Check if the string contains a specific substring
boolean containsHello = sentence.contains("Hello");
pattern & matches
String phoneNumber = "123-456-7890";
// Check if the string matches a regular expression for a phone number
boolean isValidPhoneNumber = phoneNumber.matches("\\d{3}-\\d{3}-\\d{4}");
charAt & substring()
//returns a character at a given index i
str.chatAt(i);
str.substring(i,j);//index j not included
str.substring(i);//from i till end
str.substring(i,str.length());// same as str.substring(i)
indexOf & lastIndexOf
//2 if "er" begins from index 1, -1 if not Found
str.indexOf("er");
str.indexOf("er", 2); //start the search from index 2

str.lastIndexOf("ew");//searches right to left
str.lastIndexOf("ew", 5);//right to left, from index 5
case change
str.toLowerCase();
str.toUpperCase();
replace $ replaceAll
str.replace("old","new");//String Replace
System.out.println(str.replace("a","$$"));
System.out.println(str.replace('e','*'));//Character Replace
        
String str1 = str.replaceAll(" ", "" );//Replace All, takes RegEx
String to Char Array to String
String str = "Pneumonia";
char[] c = str.toLowerCase().toCharArray();
Arrays.sort(c);//Returns a null

String revStr = new String(c);
Turn anything into String
char c = 'C';
int d = 5;
Integer i = 5;
String newStr = String.valueOf(i));

char[] c = {'T','e','s','t'};
String newStr = String.valueOf(c);
String Joining
String whiteSpace = "  sentence with white space  ";

String join = String.join(",", whiteSpace.trim(),"abc");
        
// No more Off-By-One Issue
String joinFromList = String.join(", ", list));

String combinedString = list.stream()
            .map(String::toUpperCase)
            .collect(Collectors.joining(" && ");