🧵 Java String Notes – Page 1
🌟 Introduction to Strings in Java
• A String in Java is a sequence of characters.
• Defined in the [Link] 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";
[Link]([Link]()); // 6
[Link]([Link](1)); // p
[Link]([Link](1, 4)); // pen
🧵 Java String Notes – Page 2
🔄 Loop through a String
Using for loop:
String text = "Loop";
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i) + " ");
}
// Output: L o o p
Using for-each with toCharArray():
for (char c : [Link]()) {
[Link](c);
}
🔁 Reverse a String using Loop
🧪 Code:
String original = "Java";
String reversed = "";
for (int i = [Link]() - 1; i >= 0; i--) {
reversed += [Link](i);
}
[Link]("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 < [Link]() / 2; i++) {
if ([Link](i) != [Link]([Link]() - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome)
[Link](str + " is a Palindrome");
else
[Link](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";
[Link](a == b); // false
[Link]([Link](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");
[Link](" World");
[Link](sb); // Hello World
🎯 Additional Useful Methods
• replace(char old, char new)
• trim()
• split(String regex)
• startsWith() / endsWith()
Example:
String data = " Hello World ";
[Link]([Link]()); // "Hello World"
[Link]([Link](" ", "_")); // "__Hello_World__"
🔚 Conclusion
• Strings are central to Java applications.
• Know how to use loops, conditions, and String methods.
• For efficient string modifications, prefer StringBuilder.