🧵 Java String Notes – Page 1
🌟 Introduction to Strings in Java
• A String in Java is a sequence of characters.
• Defined in the java.lang package.
• Strings are immutable (cannot be changed once created).
String name = "Java";
🔹 Ways to Create a String
1. Using String literal
String s1 = "Hello";
2. Using new keyword
String s2 = new String("Hello");
Both will create string objects but the literal goes into the String pool, while new creates in heap
memory.
📌 Common String Methods
Method Description
length() Returns string length
charAt(int index) Character at given index
substring(int start, int end) Extracts substring
toUpperCase() / toLowerCase() Case conversion
equals() / equalsIgnoreCase() Compare strings
contains() Checks for sequence
indexOf() / lastIndexOf() Position of characters
String s = "OpenAI";
System.out.println(s.length()); // 6
System.out.println(s.charAt(1)); // p
System.out.println(s.substring(1, 4)); // pen
🧵 Java String Notes – Page 2
🔄 Loop through a String
Using for loop:
String text = "Loop";
for (int i = 0; i < text.length(); i++) {
System.out.print(text.charAt(i) + " ");
}
// Output: L o o p
Using for-each with toCharArray():
for (char c : text.toCharArray()) {
System.out.println(c);
}
🔁 Reverse a String using Loop
🧪 Code:
String original = "Java";
String reversed = "";
for (int i = original.length() - 1; i >= 0; i--) {
reversed += original.charAt(i);
}
System.out.println("Reversed: " + reversed); // Output: avaJ
✅ Tip: Using StringBuilder is more efficient for large strings.
🧵 Java String Notes – Page 3
🔄 Check if a String is Palindrome using Loop
🧪 Code:
String str = "madam";
boolean isPalindrome = true;
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome)
System.out.println(str + " is a Palindrome");
else
System.out.println(str + " is NOT a Palindrome");
🧠 Logic:
- Compare characters from both ends.
- Loop till the middle of the string.
🧾 String Comparison
equals() vs ==
• == → compares references.
• equals() → compares content.
String a = new String("Hello");
String b = "Hello";
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
🧵 Java String Notes – Page 4
🧱 StringBuilder vs String
Feature String StringBuilder
Mutability Immutable Mutable
Performance Slower Faster for edits
Thread-safe No No (use StringBuffer if
needed)
Example:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb); // Hello World
🎯 Additional Useful Methods
• replace(char old, char new)
• trim()
• split(String regex)
• startsWith() / endsWith()
Example:
String data = " Hello World ";
System.out.println(data.trim()); // "Hello World"
System.out.println(data.replace(" ", "_")); // "__Hello_World__"
🔚 Conclusion
• Strings are central to Java applications.
• Know how to use loops, conditions, and String methods.
• For efficient string modifications, prefer StringBuilder.