- What is a String in Java?
A String in Java is a sequence of characters enclosed in double quotes.
String name = "Mapla";
👉 Internally, Java treats strings as objects, not primitive types.
2.Why Strings are Important?
- Used for storing text data
- Helps in user input/output
- Used in file handling, web apps, APIs, etc.
3.String is Immutable
In Java, Strings are immutable (cannot be changed).
String str = "Hello";
str.concat(" World");
System.out.println(str);
👉 Output: "Hello" (not changed
)
✔ Reason: A new object is created instead of modifying the original one.
4.Common String Methods
- length()
Returns number of characters
String str = "Mapla";
System.out.println(str.length()); // 5
- charAt()
Returns character at specific index
System.out.println(str.charAt(0)); // M
- toUpperCase() & toLowerCase()
System.out.println(str.toUpperCase()); // MAPLA
System.out.println(str.toLowerCase()); // mapla
- equals()
Compares two strings
String a = "Java";
String b = "Java";
System.out.println(a.equals(b)); // true
- contains()
Check substring exists or not
System.out.println(str.contains("pla")); // true
- substring()
Extract part of string
System.out.println(str.substring(0, 3)); // Map
- replace()
Replace characters
System.out.println(str.replace("Map", "Top")); // Topla
- String vs StringBuilder vs StringBuffer
Feature| String| StringBuilder| StringBuffer
Mutable| ❌ No| ✅ Yes| ✅ Yes
Thread Safe| ❌ No| ❌ No| ✅ Yes
Performance| Slow| Fast| Medium
👉 Use:
- String → normal usage
- StringBuilder → performance (single thread)
- StringBuffer → thread-safe apps
- Removing Duplicate Characters Example
String str = "aabbccdd";
String result = "";
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(result.indexOf(c) == -1) {
result += c;
}
}
System.out.println(result); // abcd
- Tips for Interviews
- String is immutable
- Stored in String Pool
- Use ".equals()" instead of "=="
- Prefer StringBuilder in loops

Top comments (0)