Codectionary / Developer documentation / Java

Strings & String Methods

String is one of the most heavily used classes in Java, representing an immutable sequence of characters - once created, a String's content can never change, and every 'modifying' method actually returns a brand new String. Java offers a rich set of built-in methods for common operations like extracting substrings, searching, splitting, and case conversion.

Syntax

String variableName = "text";

Examples

Creating and Combining Strings

Basic string creation and concatenation.

String firstName = "John";
String lastName = "A";

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

String greeting = String.format("Hello, %s!", firstName);
System.out.println(greeting);

Common String Methods

Length, case conversion, and trimming whitespace.

String text = "  Hello World  ";

System.out.println(text.length());       // 15 (includes whitespace)
System.out.println(text.trim());          // "Hello World"
System.out.println(text.toUpperCase());   // "  HELLO WORLD  "
System.out.println(text.toLowerCase());   // "  hello world  "

Searching and Extracting Substrings

Finding content within a string and pulling out parts of it.

String sentence = "The quick brown fox";

System.out.println(sentence.contains("quick"));    // true
System.out.println(sentence.indexOf("brown"));      // 10
System.out.println(sentence.substring(4, 9));        // "quick"
System.out.println(sentence.replace("fox", "dog"));  // The quick brown dog

Splitting and Joining

Converting between a string and an array of strings.

String csv = "John,Zain,Jamal";
String[] names = csv.split(",");

for (String name : names) {
    System.out.println(name);
}

String joined = String.join(" & ", names);
System.out.println(joined);  // John & Zain & Jamal

Best practices

  • Remember String is immutable - every method like .trim() or .toUpperCase() returns a new String rather than modifying the original
  • Use a StringBuilder instead of repeated + concatenation when building a string inside a loop, for much better performance
  • Use .equals() (or .equalsIgnoreCase()) for content comparison, never == for comparing String values
  • Use String.format() or printf-style formatting for building strings with embedded numbers or aligned output, rather than manual concatenation

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading