Skip to content

Java Characters and Strings

Text processing is a common task in programming. Java provides the char primitive type to represent a single character, and a very powerful String class to handle character sequences.

char Type

The char type is used to store a single 16-bit Unicode character. Its value must be enclosed in single quotes (').

java
char myInitial = 'C';
char copyrightSymbol = '©';
char chineseChar = 'H';

// Can also use Unicode values to represent characters
char unicodeChar = '\u0041'; // Represents 'A'

System.out.println("My initial: " + myInitial);
System.out.println("Unicode char: " + unicodeChar);

String Class

String is a reference type used to represent a sequence of characters. It is one of the most commonly used and important classes in Java.

Creating Strings

The simplest way to create a string is using double quotes (").

java
// Create directly using literals
String greeting = "Hello, World!";

// Create String object using new keyword
String name = new String("Java");

String Immutability

This is the most important characteristic of the String class: Once a String object is created, its value cannot be changed.

When you "modify" a string (such as concatenation, replacement), Java actually creates a new String object rather than modifying the original object in place.

java
String s = "Hello";
s = s.concat(", Java!"); // concat method returns a new string object

System.out.println(s); // Output "Hello, Java!"
// The original "Hello" string object still exists in memory, but the s variable no longer references it

This design makes strings thread-safe in multi-threaded environments and allows them to be safely used as hash table keys.

Common String Methods

The String class provides numerous useful methods for manipulating strings. Here are some of the most common:

  • length(): Returns the length (number of characters) of the string.

    java
    String str = "Java";
    System.out.println(str.length()); // 4
  • charAt(int index): Returns the char at the specified index position. Index starts from 0.

    java
    String str = "Java";
    System.out.println(str.charAt(0)); // 'J'
  • concat(String str): Concatenates the specified string to the end of this string. Equivalent to the + operator.

    java
    String s1 = "Hello, ";
    String s2 = "World";
    System.out.println(s1.concat(s2)); // "Hello, World"
  • equals(Object anObject): Compares if the contents of two strings are exactly the same (case-sensitive).

  • equalsIgnoreCase(String anotherString): Compares if the contents of two strings are the same (case-insensitive).

    java
    String s1 = "java";
    String s2 = "Java";
    System.out.println(s1.equals(s2)); // false
    System.out.println(s1.equalsIgnoreCase(s2)); // true
  • substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string. Includes beginIndex, excludes endIndex.

    java
    String str = "HelloWorld";
    System.out.println(str.substring(0, 5)); // "Hello"
  • indexOf(String str): Returns the index of the first occurrence of the specified substring in this string. Returns -1 if not found.

    java
    String str = "Hello World";
    System.out.println(str.indexOf("World")); // 6
  • toUpperCase() / toLowerCase(): Returns a new string with all characters converted to uppercase or lowercase.

  • trim(): Returns a new string with whitespace removed from both ends of the original string.

  • replace(char oldChar, char newChar): Returns a new string where all oldChar are replaced with newChar.

  • split(String regex): Splits this string around matches of the given regular expression, returning a string array.

    java
    String data = "apple,banana,orange";
    String[] fruits = data.split(",");
    for (String fruit : fruits) {
        System.out.println(fruit);
    }
  • startsWith(String prefix) / endsWith(String suffix): Tests if this string starts with the specified prefix or ends with the specified suffix.

  • isEmpty(): Checks if string length is 0. Available from Java 6.

  • isBlank(): Checks if string is blank (length is 0 or contains only whitespace). Available from Java 11.

StringBuilder and StringBuffer

Since String is immutable, when you need to frequently modify string content (for example, concatenating many strings in a loop), using String creates many unnecessary intermediate objects and is inefficient.

To solve this problem, Java provides two mutable string classes:

  • StringBuilder: Not thread-safe, but more efficient. Preferred for string modification in single-threaded environments.
  • StringBuffer: Thread-safe, but slightly less efficient. Suitable for multi-threaded environments.

They provide methods like append(), insert(), delete(), replace() to directly modify string content without creating new objects each time.

java
// Efficient string concatenation
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", ");
sb.append("World!");

String result = sb.toString(); // Convert to String object at the end
System.out.println(result);

Content is for learning and research only.