Java Strings

A String in Java is a sequence of characters. It is used to represent text — like names, messages, addresses, or any combination of letters, digits, and symbols. In Java, String is not a primitive type — it is a class, which means it comes with a rich set of built-in methods to manipulate and work with text.

Creating a String

Strings in Java are enclosed in double quotes. There are two common ways to create a string:

Method 1 – String Literal (Most Common)

String greeting = "Hello, Java!";

Java stores string literals in a special memory area called the String Pool. If the same string literal is used again, Java reuses the existing object rather than creating a new one.

Method 2 – Using the new Keyword

String greeting = new String("Hello, Java!");

This always creates a new String object in memory, even if the same content already exists in the String Pool. Using the literal form is preferred.

String Immutability

Strings in Java are immutable. Once a String object is created, its value cannot be changed. When an operation appears to modify a string, it actually creates a new string object.

String name = "Alice";
name = name + " Smith";   // A new String object is created; "Alice" remains unchanged
System.out.println(name); // Alice Smith

Common String Methods

The String class provides many useful methods. Here are the most commonly used ones:

length()

Returns the number of characters in the string.

String city = "London";
System.out.println(city.length());   // 6

charAt(index)

Returns the character at a specific position. String indexing starts at 0.

String word = "Java";
System.out.println(word.charAt(0));   // J
System.out.println(word.charAt(2));   // v

substring(start) and substring(start, end)

Extracts a portion of the string.

String sentence = "Hello World";
System.out.println(sentence.substring(6));      // World
System.out.println(sentence.substring(0, 5));   // Hello

indexOf(value)

Returns the index (position) of the first occurrence of a character or substring. Returns -1 if not found.

String text = "I love Java";
System.out.println(text.indexOf("Java"));   // 7
System.out.println(text.indexOf("Python")); // -1

toUpperCase() and toLowerCase()

Converts the string to all uppercase or all lowercase characters.

String message = "Hello, World!";
System.out.println(message.toUpperCase());   // HELLO, WORLD!
System.out.println(message.toLowerCase());   // hello, world!

trim()

Removes leading and trailing white spaces (spaces, tabs, newlines).

String raw = "   Java   ";
System.out.println(raw.trim());   // "Java"

replace(old, new)

Replaces all occurrences of a character or substring with a new one.

String sentence = "I like cats";
System.out.println(sentence.replace("cats", "dogs"));   // I like dogs

contains(value)

Returns true if the string contains the specified sequence.

String phrase = "Learn Java Programming";
System.out.println(phrase.contains("Java"));    // true
System.out.println(phrase.contains("Python"));  // false

startsWith() and endsWith()

Checks whether the string starts or ends with a particular prefix or suffix.

String filename = "report_2024.pdf";
System.out.println(filename.startsWith("report"));   // true
System.out.println(filename.endsWith(".pdf"));        // true

equals() and equalsIgnoreCase()

Compares two strings for equality. Use equals(), not ==, to compare string content.

String s1 = "java";
String s2 = "Java";
System.out.println(s1.equals(s2));             // false
System.out.println(s1.equalsIgnoreCase(s2));   // true

Important: Using == on strings compares memory addresses, not content. Always use equals() for content comparison.

split(delimiter)

Splits the string into an array of substrings based on a delimiter.

String fruits = "apple,banana,cherry";
String[] parts = fruits.split(",");

for (String fruit : parts) {
    System.out.println(fruit);
}

Output:

apple
banana
cherry

isEmpty() and isBlank()

isEmpty() returns true if the string has zero characters. isBlank() returns true if the string is empty or contains only whitespace.

String a = "";
String b = "   ";
System.out.println(a.isEmpty());    // true
System.out.println(b.isEmpty());    // false
System.out.println(b.isBlank());    // true

String Concatenation

Strings can be joined using the + operator or the concat() method.

String firstName = "John";
String lastName = "Doe";

String fullName = firstName + " " + lastName;
System.out.println(fullName);   // John Doe

// Using concat()
String combined = firstName.concat(" ").concat(lastName);
System.out.println(combined);   // John Doe

String Formatting

The String.format() method creates a formatted string without printing it immediately.

String result = String.format("Student: %s | Score: %.2f", "Alice", 95.678);
System.out.println(result);   // Student: Alice | Score: 95.68

StringBuilder – For Efficient String Building

When strings need to be modified repeatedly (like in a loop), StringBuilder is much more efficient than repeatedly creating new String objects. It is mutable, meaning its content can be changed without creating a new object each time.

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", ");
sb.append("World!");
System.out.println(sb.toString());   // Hello, World!

sb.insert(5, " there");
System.out.println(sb.toString());   // Hello there, World!

sb.delete(5, 11);
System.out.println(sb.toString());   // Hello, World!

sb.reverse();
System.out.println(sb.toString());   // !dlroW ,olleH

Summary

  • A String in Java is an immutable sequence of characters.
  • Strings are created using double quotes: "Hello".
  • String content comparison must use equals(), not ==.
  • Commonly used methods: length(), charAt(), substring(), indexOf(), replace(), toUpperCase(), split(), trim().
  • Use StringBuilder when building or modifying strings frequently for better performance.

Leave a Comment

Your email address will not be published. Required fields are marked *