DEV Community

KIRAN RAJ
KIRAN RAJ

Posted on

String in java

  1. 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
)
Enter fullscreen mode Exit fullscreen mode

✔ 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
Enter fullscreen mode Exit fullscreen mode

  • charAt()

Returns character at specific index

System.out.println(str.charAt(0)); // M

Enter fullscreen mode Exit fullscreen mode

  • toUpperCase() & toLowerCase()
System.out.println(str.toUpperCase()); // MAPLA
System.out.println(str.toLowerCase()); // mapla
Enter fullscreen mode Exit fullscreen mode

  • equals()

Compares two strings

String a = "Java";
String b = "Java";

System.out.println(a.equals(b)); // true
Enter fullscreen mode Exit fullscreen mode

  • contains()

Check substring exists or not

System.out.println(str.contains("pla")); // true

Enter fullscreen mode Exit fullscreen mode

  • substring()

Extract part of string

System.out.println(str.substring(0, 3)); // Map

Enter fullscreen mode Exit fullscreen mode

  • replace()

Replace characters

System.out.println(str.replace("Map", "Top")); // Topla

Enter fullscreen mode Exit fullscreen mode

  1. 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

  1. 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

Enter fullscreen mode Exit fullscreen mode

  1. Tips for Interviews
  • String is immutable
  • Stored in String Pool
  • Use ".equals()" instead of "=="
  • Prefer StringBuilder in loops

Top comments (0)