In this blog, we are going to learn about Strings, and how do we use them in Java.
- A string is a sequence of characters.
- String is a class in Java.
- String is immutable; the value once created can’t be changed.
- String is not a premitive data type.
Why are String immutable?
Strings are immutable on purpose. Because in order to optimize Strings in Java, we have String Pool, where all the strings recides.
Whenever a new string is created, first the Java Program checks the String Pool, and if the same string is present, the new reference points to the same string literal. This saves memory (by using the same literal).
And since the same memory block can be shared between multiple references, and if one change it, the changes will also impact the other references, that’s why Strings in Java are immutable.

Methods of String Class
In Java, String is a class with a lot of methods. Here is a list of some of the imporant methods, which are going to help in solving DSA questions later.
package StringPractice;
public class MethodsOfString {
public static void main(String[] args) {
String name = "Pumbcode";
//1. Length
System.out.println("Length: " + name.length());
//2. chatAt
System.out.println("chatAt: " + name.charAt(7));
//3. Compare two Strings
String str1 = "Code";
String str2 = new String("Code");
System.out.println("str1 == str2: " + (str1 == str2));
System.out.println("Equals: " + str1.equals(str2));
//4. compareTo
System.out.println("str1.compareTo(str2): " + str1.compareTo(str2));
System.out.println('A' + 0);
//5. substring
String fullName = "Akshay Agarwal (Pumbcode)";
fullName.substring(7);
System.out.println(fullName.substring(7)); // Include 7 index
System.out.println(fullName.substring(7, 14)); // Include 7 index, Last Index is not included
//6. toUpperCase()
System.out.println(fullName.toUpperCase());
//7. toLowerCase()
System.out.println(fullName.toLowerCase());
//8. trim()
String stringWithSpaces = " This is our string. ";
System.out.println(stringWithSpaces.trim());
//9. replace()
System.out.println(stringWithSpaces.replace(' ', '.'));
System.out.println(stringWithSpaces.replace("This", "That"));
//10. contains()
System.out.println("Sunshine".contains("Sun"));
//11. startsWith
System.out.println("Sunshine".startsWith("Sun"));
//12. endsWith
System.out.println("Sunshine".endsWith("shine"));
//13. isEmpty()
System.out.println(" ".isEmpty());
//14. isBlank()
System.out.println(" ".isBlank());
//15. indexOf
System.out.println("Sunshine".indexOf("n"));
//16. lastIndexOf
System.out.println("Sunshine".lastIndexOf("n"));
}
}
Question 1: Reverse of a String
This is the first approach, in this we are directly using a String to append new values in that, here the major problem is that as String is immutable, every append in the String (reverse), is going to add a new block/string literal in String Pool, which is simply waste of memory.
// Not a good solution, because, through reverse, we will create multiple string literals into the memory
public static String reverse(String str) {
String reverse = "";
for (int i = str.length() - 1; i >= 0; i--) {
reverse += str.charAt(i);
}
return reverse;
}
Now we are jumping to one more solution, which is by using the predefined method of the StringBuilder class. This is a good and optimise way of solving the problem, but the issue with this is this doesn’t show us how you think, that is not going to help in interviews.
// Using StringBuilder
public static String reverseUsingSB(String str) {
StringBuilder sb = new StringBuilder(str);
sb.reverse();
return sb.toString();
}
So we have to now think of a solution which is optimise, and interview worthy, which shows clear thinking and approach to draw an optimal solution.
// Using two pointers
public static String reverseUsing2Pointer(String str) {
char[] arr = str.toCharArray();
int left = 0;
int right = arr.length - 1;
while(left < right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return new String(arr);
}
Question 2: Palindrome
I am only doing palindrome code in the optimal way this time, here also we can use StringBuilder, if you are also from java background, try using StringBuilder, and let me know in the comments.
From the following code, you can check any string, from smaller strings, like MADAM, to large lines, like “A man, a plan, a canal: Panama
“
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while(left < right) {
if (!Character.isLetterOrDigit(str.charAt(left)) ) {
left++;
continue;
}
if (!Character.isLetterOrDigit(str.charAt(right)) ) {
right--;
continue;
}
if ( Character.toLowerCase(str.charAt(left)) != Character.toLowerCase(str.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
Question3: Ccount Vowels & Consonants
public static void countVowelsAndConsonants(String str) {
int vowel = 0;
int consonant = 0;
int i = 0;
while (i<str.length()) {
char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowel++;
} else {
consonant++;
}
i++;
}
System.out.println("Vowel: " + vowel);
System.out.println("Consonants: " + consonant);
}
Question 4. Frequency of Each Character in a String
public static void countFrequency(String str) {
Map<Character, Integer> count = new HashMap<>();
for (char ch: str.toCharArray()) {
count.put(ch, count.getOrDefault(ch, 0) + 1);
}
for ( Map.Entry<Character, Integer> entry: count.entrySet() ) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
Question 5. Get First Non-Repeating Character in a String
// Can't use predefined method
public static String transform(String str, String wordToReplace, String wordWithReplace) {
return str.replace(wordToReplace, wordWithReplace);
}
public static char getFirstNonRepeatingCharacter(String str) {
Map<Character, Integer> count = new HashMap<>();
for (char ch: str.toCharArray()) {
count.put(ch, count.getOrDefault(ch, 0) + 1);
}
for (char ch: str.toCharArray()) {
if (count.get(ch) == 1) {
return ch;
}
}
return '-';
}
Question 6. Replace String: Sun and Sunshine to Moon and Moonshine
public static String betterTransform(String str, String wordToReplace, String wordWithReplace) {
StringBuilder stringBuilder = new StringBuilder();
int index = 0;
while (index < str.length()) {
if (index + wordToReplace.length() < str.length() &&
str.substring(index, index+wordToReplace.length()).equals(wordToReplace)) {
stringBuilder.append(wordWithReplace);
index += wordToReplace.length();
} else {
stringBuilder.append(str.charAt(index));
index++;
}
}
return stringBuilder.toString();
}
