String Basics

Creating and using String objects

Interview Relevant: String immutability is frequently tested
7 min read

Strings in Java

In Java, String is a special class (not a primitive) that represents a sequence of characters. Strings are immutable - once created, they cannot be changed.

Creating Strings

  • String literal: "Hello" - stored in String Pool
  • new keyword: new String("Hello") - creates new object in heap

🔑 Key Point: String is a class in java.lang package. It's automatically imported and can be used without explicit import.

String Characteristics

  • Immutable: Content cannot change after creation
  • Final class: Cannot be extended
  • Thread-safe: Safe to share between threads
  • Backed by char[]: (Java 8) or byte[] (Java 9+)

⚠️ Important: Never compare strings with ==! Always use .equals() or .equalsIgnoreCase().

Code Examples

Different ways to create and compare strings

java
1// Creating strings - different ways
2String s1 = "Hello";                    // String literal (String Pool)
3String s2 = "Hello";                    // Same reference as s1
4String s3 = new String("Hello");        // New object in heap
5String s4 = new String("Hello");        // Different object than s3
6
7// Reference comparison
8System.out.println(s1 == s2);           // true (same pool reference)
9System.out.println(s1 == s3);           // false (different objects)
10System.out.println(s3 == s4);           // false (different objects)
11
12// Content comparison
13System.out.println(s1.equals(s3));      // true (same content)
14
15// Empty and blank strings
16String empty = "";
17String blank = "   ";
18System.out.println(empty.isEmpty());    // true
19System.out.println(blank.isBlank());    // true (Java 11+)

String concatenation and immutability

java
1// String concatenation
2String first = "Hello";
3String second = "World";
4
5// Using + operator
6String combined = first + " " + second;  // "Hello World"
7
8// Using concat() method
9String joined = first.concat(" ").concat(second);
10
11// String with other types
12int age = 25;
13String message = "Age: " + age;  // "Age: 25" (auto-conversion)
14
15// Multiple concatenation (inefficient - use StringBuilder)
16String result = "";
17for (int i = 0; i < 5; i++) {
18    result += i;  // Creates new String each time!
19}
20
21// Immutability demonstration
22String original = "Hello";
23String modified = original.toUpperCase();
24System.out.println(original);   // "Hello" (unchanged!)
25System.out.println(modified);   // "HELLO" (new object)

Basic String operations

java
1// Common String operations
2String str = "Hello, World!";
3
4// Length
5System.out.println(str.length());       // 13
6
7// Character access
8System.out.println(str.charAt(0));      // 'H'
9System.out.println(str.charAt(7));      // 'W'
10
11// Substring
12System.out.println(str.substring(0, 5));     // "Hello"
13System.out.println(str.substring(7));        // "World!"
14
15// Case conversion
16System.out.println(str.toUpperCase());  // "HELLO, WORLD!"
17System.out.println(str.toLowerCase());  // "hello, world!"
18
19// Search
20System.out.println(str.indexOf('o'));        // 4 (first occurrence)
21System.out.println(str.lastIndexOf('o'));    // 8 (last occurrence)
22System.out.println(str.contains("World"));   // true

Type conversions with Strings

java
1// String to other types
2String numStr = "123";
3int num = Integer.parseInt(numStr);
4double dbl = Double.parseDouble("3.14");
5
6// Other types to String
7String fromInt = String.valueOf(42);
8String fromDouble = String.valueOf(3.14);
9String fromBool = String.valueOf(true);
10String fromChar = String.valueOf('A');
11
12// Array to String
13char[] chars = {'H', 'e', 'l', 'l', 'o'};
14String fromChars = new String(chars);
15String fromChars2 = String.valueOf(chars);
16
17// String to char array
18char[] charArray = "Hello".toCharArray();
19
20// Text blocks (Java 15+)
21String textBlock = """
22    This is a
23    multi-line
24    string
25    """;

Use Cases

  • Text processing and manipulation
  • User input handling
  • Configuration values
  • File path construction
  • Data parsing and formatting
  • Message building

Common Mistakes to Avoid

  • Using == instead of equals() for comparison
  • Concatenating strings in loops (use StringBuilder)
  • Not handling null strings
  • ArrayIndexOutOfBounds with charAt()
  • Assuming String is primitive type
  • Not understanding immutability