What is a String in Java?
A String is a sequence of characters like words, sentences, or any text data. In Java, Strings are immutable, meaning
once you create a String object, you cannot change its content. If you try to modify it, a new String object is created
behind the scenes.
Companies: Amazon, Microsoft
How are Strings stored in Java memory?
Java stores Strings in two places:
• String constant pool: Special memory area where string literals are stored and reused to save memory.
• Heap memory: When you create a String with new String(), it’s stored in the heap and not pooled by
default.
Why it matters: Helps optimize memory by avoiding duplicate strings.
Companies: Google, Facebook
What does immutability mean for String?
Once a String is created, you cannot change its characters. Methods like replace() or concat() don’t modify
the original string; instead, they return a new string with the changes.
Why it matters: This property allows Strings to be safely shared between multiple parts of a program
without risk of unexpected changes.
Companies: Amazon, IBM
Difference between String, StringBuilder, and StringBuffer?
• String: Immutable, safest but costly if frequently modified.
• StringBuilder: Mutable (can be changed), faster for single-threaded programs.
• StringBuffer: Mutable and thread-safe (synchronized), used when multiple threads access the string.
Why it matters: Choosing the right class affects performance and thread safety.
Companies: Google, Microsoft
What is string concatenation? How to do it?
• Concatenation means joining two or more strings. You can use the + operator or .concat() method. For
example: "Hello" + " World" → "Hello World".
Why it matters: Efficient concatenation matters in performance-critical applications.
Companies: IBM, Infosys
JAVA BY KRISHNA
What is the string pool?
A string pool is a special memory region inside the Java heap where String literals are stored uniquely. If a
string literal already exists in the pool, Java reuses that object instead of creating a new one.
Why it matters: Saves memory and speeds up string comparison using ==.
Companies: Facebook, Microsoft
How to create a String?
You can create a String in two ways:
• Using string literals: String s = "Hello"; (stored in string pool).
• Using constructor: String s = new String("Hello"); (new object in heap).
Why it matters: Literal strings are reused, constructors create new objects.
Companies: Amazon, TCS
Difference between == and .equals() for Strings?
• == compares if both variables point to the same object in memory.
• .equals() compares the actual content inside the strings.
Example:
String a = "abc";
String b = new String("abc");
a == b; // false, different objects
a.equals(b); // true, contents same
Companies: Amazon, Cisco
What does .intern() do?
• If you create a String not in the pool (for example, using new String("hello")), calling .intern() adds it
to the pool if it’s not there yet.
• If the pool already has that String, .intern() returns the reference to the existing one in the pool.
JAVA BY KRISHNA
• This way, you can save memory by reusing String objects.
Example to clarify:
String s1 = "hello"; // String literal, goes to String Pool
String s2 = new String("hello"); // New String object, NOT in pool
String s3 = s2.intern(); // s3 refers to String Pool "hello"
System.out.println(s1 == s2); // false, because s2 is different object
System.out.println(s1 == s3); // true, both refer to the same String Pool object
• s1 == s3 is true because both point to the same object in the String Pool.
• s1 == s2 is false because s2 is a new String object on the heap, not the pool.
What is string interning?
Interning means adding a String object to the string pool using .intern() method. If a string with the same
content already exists in the pool, that reference is returned. Otherwise, it adds the new string to the pool.
Why it matters: Helps save memory and enables faster comparisons.
Companies: Google, Microsoft
Why does it matter?
• Memory efficient: Avoids multiple copies of the same String.
• Faster comparisons: You can compare interned Strings using == instead of .equals(), which is quicker
How to convert String to int?
Use Integer.parseInt("123") to convert the string "123" into integer 123. If the string doesn’t contain a valid
number, it throws NumberFormatException.
Why it matters: Common when reading numeric data from user input or files.
Companies: Microsoft, Amazon
JAVA BY KRISHNA
How to get the length of a String?
Use .length() method which returns the number of characters in the string.
Example: "hello".length() → 5.
Why it matters: Knowing length helps in iteration and validation.
Companies: Infosys, Amazon
How to find a character at a specific index?
Use .charAt(index). Index starts at 0, so str.charAt(0) returns the first character.
Example: "hello".charAt(1) → 'e'.
Why it matters: Access individual characters when processing strings.
Companies: Google, Microsoft
How to check if a string contains another string?
Use .contains("sub"). Returns true if substring exists, else false.
Example: "hello world".contains("world") → true.
Why it matters: Useful for search operations inside strings.
Companies: Amazon, Facebook
How to convert a string to lowercase/uppercase?
Use .toLowerCase() or .toUpperCase() to convert all letters to lower or upper case respectively.
Example: "Hello".toUpperCase() → "HELLO".
Why it matters: Normalize strings for comparison or display.
Companies: Microsoft, Accenture
How to trim whitespace from a string?
Use .trim() to remove leading and trailing spaces but not spaces inside the string.
Example: " hello ".trim() → "hello".
Why it matters: Clean input before processing or storing.
Companies: Infosys, Amazon
How to replace characters or substrings?
Use .replace(oldChar, newChar) or .replace("old", "new") to replace characters or substrings.
Example: "hello".replace('l', 'p') → "heppo".
Why it matters: Modify strings safely and easily.
Companies: Microsoft, IBM
How to split a string?
JAVA BY KRISHNA
Use .split(delimiter) to break a string into parts based on the delimiter.
Example: "a,b,c".split(",") → array ["a", "b", "c"].
Why it matters: Parsing CSV or formatted data.
Companies: Amazon, Google
How to check if a string starts or ends with a substring?
Use .startsWith("prefix") or .endsWith("suffix").
Example: "hello".startsWith("he") → true.
Why it matters: Validate or filter strings.
Companies: Infosys, TCS
How to check if a string is empty?
Use .isEmpty() which returns true if the string has no characters (length is 0).
Example: "".isEmpty() → true.
Why it matters: Input validation.
Companies: Amazon, Infosys
How to convert String to char array?
Use .toCharArray() method. For example, "hello".toCharArray() returns ['h', 'e', 'l', 'l', 'o'].
Why it matters: When you need to manipulate individual characters.
Companies: Infosys, IBM
How to convert char array to String?
You create a new String object from a char array: new String(charArray).
Example: new String(new char[]{'h','i'}) → "hi".
Why it matters: Converts character arrays back into string form after processing.
Companies: Microsoft, Wipro
How to check if a string contains only digits?
Use .matches("\\d+") which checks if the string consists of one or more digits.
Example: "12345".matches("\\d+") → true, "123a".matches("\\d+") → false.
Why it matters: Input validation for numeric strings.
How to remove all spaces from a string?
JAVA BY KRISHNA
Use .replace(" ", "") to remove every space character.
Example: "a b c".replace(" ", "") → "abc".
Why it matters: Clean strings before processing.
Companies: Microsoft, IBM
Write a program to reverse the given string?
1. import java.lang.String;
2.
3. public class demo {
4. public static String reverse(String str) {
5. StringBuilder sb = new StringBuilder(str);
6. return sb.reverse().toString();
7. }
8.
9. public static void main(String[] args) {
10. String input = "krishna";
11. String result = reverse(input);
12. System.out.println("reversed string is:" + result);
13. }
14. }
Write a program to reverse the string:
Reverse the input string in-place.
public class ReverseString {
public static void main(String[] args) {
char[] s = {'h', 'e', 'l', 'l', 'o'};
reverseString(s);
System.out.println(java.util.Arrays.toString(s)); // [o, l, l, e, h]
}
public static void reverseString(char[] s) {
int left = 0, right = s.length - 1;
while (left < right) {
char temp = s[left];
s[left++] = s[right];
s[right--] = temp;
}
JAVA BY KRISHNA
}
}
Longest Common Prefix (LeetCode #14)
Find the longest common prefix among an array of strings.
public class LongestCommonPrefix {
public static void main(String[] args) {
String[] strs = {"flower", "flow", "flight"};
System.out.println(longestCommonPrefix(strs)); // "fl"
}
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return "";
}
}
return prefix;
}
}
write a program to check that whether the string is palindrome or not?
public class demo {
public static boolean check_palindrome(String str) {
int start = 0, end = str.length() - 1;
while (start < end) {
if (str.charAt(start) != str.charAt(end)) {
JAVA BY KRISHNA
return false;
start++;
end--;
return true;
public static void main(String[] args) {
String input = "krishna";
boolean palindrome = check_palindrome(input);
if (palindrome) {
System.out.println("palindrome number");
} else {
System.out.println("not palindrome number");
Count Occurrence of a Character
public class CharCount {
public static void main(String[] args) {
String str = "hello world";
char ch = 'l';
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
JAVA BY KRISHNA
}
System.out.println("Occurrences of '" + ch + "': " + count);
Remove Duplicate Characters from String
import java.util.LinkedHashSet;
import java.util.Set;
public class RemoveDuplicates {
public static void main(String[] args) {
String str = "programming";
String result = removeDuplicates(str);
System.out.println("After removing duplicates: " + result);
public static String removeDuplicates(String str) {
Set<Character> set = new LinkedHashSet<>();
for (char c : str.toCharArray()) {
set.add(c);
StringBuilder sb = new StringBuilder();
for (char c : set) {
sb.append(c);
return sb.toString();
}
JAVA BY KRISHNA
Check if Two Strings Are Anagrams
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent";
if (areAnagrams(s1, s2)) {
System.out.println(s1 + " and " + s2 + " are anagrams");
} else {
System.out.println(s1 + " and " + s2 + " are not anagrams");
public static boolean areAnagrams(String s1, String s2) {
if (s1.length() != s2.length()) return false;
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
JAVA BY KRISHNA