Java String Tutorial: All String Class Methods with Examples

Introduction

Strings are one of the most fundamental and commonly used data types in Java. The java.lang.String class provides numerous methods to manipulate and handle strings effectively. This tutorial covers all the methods of the String class as of Java 21, providing examples and explanations for each method.

Table of Contents

  1. String Basics
  2. Creating Strings
    • Using String Literals
    • Using the new Keyword
    • From Character Arrays
  3. String Methods
    • charAt()
    • codePointAt()
    • codePointBefore()
    • codePointCount()
    • compareTo()
    • compareToIgnoreCase()
    • concat()
    • contains()
    • contentEquals()
    • endsWith()
    • equals() and equalsIgnoreCase()
    • getBytes()
    • getChars()
    • hashCode()
    • indexOf()
    • intern()
    • lastIndexOf()
    • length()
    • matches()
    • offsetByCodePoints()
    • regionMatches()
    • replace()
    • replaceAll()
    • replaceFirst()
    • split()
    • startsWith()
    • subSequence()
    • substring()
    • toCharArray()
    • toLowerCase()
    • toUpperCase()
    • trim()
    • valueOf()
    • strip()
    • stripLeading()
    • stripTrailing()
    • isBlank()
    • lines()
    • repeat()
    • indent()
    • transform()
    • describeConstable()
    • resolveConstantDesc()
    • formatted()
    • stripIndent()
    • translateEscapes()
  4. Conclusion

1. String Basics

Strings in Java are objects that represent a sequence of characters. The Java platform provides the java.lang.String class to create and manipulate strings. Strings are immutable, meaning once a string is created, its value cannot be changed. Instead, every modification results in the creation of a new string.

2. Creating Strings

Using String Literals

A string literal is a sequence of characters enclosed in double quotes.

public class StringLiteralExample {
    public static void main(String[] args) {
        String s = "javaguides";
        System.out.println(s); // Output: javaguides
    }
}

Using the new Keyword

You can also create strings using the new keyword.

public class NewKeywordExample {
    public static void main(String[] args) {
        String s = new String("javaguides");
        System.out.println(s); // Output: javaguides
    }
}

From Character Arrays

Strings can be created from character arrays.

public class CharArrayExample {
    public static void main(String[] args) {
        char[] chars = {'J', 'a', 'v', 'a'};
        String s = new String(chars);
        System.out.println(s); // Output: Java
    }
}

3. String Methods

charAt()

Returns the character at the specified index.

public class CharAtExample {
    public static void main(String[] args) {
        String str = "Welcome";
        char ch = str.charAt(0);
        System.out.println("Character at index 0: " + ch); // Output: W
    }
}

codePointAt()

Returns the Unicode code point at the specified index.

public class CodePointAtExample {
    public static void main(String[] args) {
        String str = "javaguides";
        int codePoint = str.codePointAt(1);
        System.out.println("Unicode code point at index 1: " + codePoint); // Output: 97
    }
}

codePointBefore()

Returns the Unicode code point before the specified index.

public class CodePointBeforeExample {
    public static void main(String[] args) {
        String str = "javaguides";
        int codePoint = str.codePointBefore(2);
        System.out.println("Unicode code point before index 2: " + codePoint); // Output: 97
    }
}

codePointCount()

Returns the number of Unicode code points in the specified text range.

public class CodePointCountExample {
    public static void main(String[] args) {
        String str = "javaguides";
        int count = str.codePointCount(0, str.length());
        System.out.println("Number of Unicode code points: " + count); // Output: 10
    }
}

compareTo()

Compares two strings lexicographically.

public class CompareToExample {
    public static void main(String[] args) {
        String s1 = "apple";
        String s2 = "banana";
        int result = s1.compareTo(s2);
        System.out.println("Comparing 'apple' with 'banana': " + result); // Output: -1
    }
}

compareToIgnoreCase()

Compares two strings lexicographically, ignoring case differences.

public class CompareToIgnoreCaseExample {
    public static void main(String[] args) {
        String s1 = "Apple";
        String s2 = "apple";
        int result = s1.compareToIgnoreCase(s2);
        System.out.println("Comparing 'Apple' with 'apple' (ignore case): " + result); // Output: 0
    }
}

concat()

Concatenates the specified string to the end of the current string.

public class ConcatExample {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = " World";
        String result = str1.concat(str2);
        System.out.println("Concatenated string: " + result); // Output: Hello World
    }
}

contains()

Returns true if and only if this string contains the specified sequence of char values.

public class ContainsExample {
    public static void main(String[] args) {
        String str = "javaguides";
        boolean result = str.contains("guides");
        System.out.println("Contains 'guides': " + result); // Output: true
    }
}

contentEquals()

Compares this string to the specified CharSequence.

public class ContentEqualsExample {
    public static void main(String[] args) {
        String str = "javaguides";
        boolean result = str.contentEquals("javaguides");
        System.out.println("Content equals 'javaguides': " + result); // Output: true
    }
}

endsWith()

Tests if this string ends with the specified suffix.

public class EndsWithExample {
    public static void main(String[] args) {
        String str = "javaguides";
        boolean result = str.endsWith("guides");
        System.out.println("Ends with 'guides': " + result); // Output: true
    }
}

equals() and equalsIgnoreCase()

Compares two strings for equality.

public class EqualsExample {
    public static void main(String[] args) {
        String s1 = "javaguides";
        String s2 = "JAVAGUIDES";
        System.out.println("Equals: " + s1.equals(s2)); // Output: false
        System.out.println("Equals ignore case: " + s1.equalsIgnoreCase(s2)); // Output: true
    }
}

getBytes()

Encodes this string into a sequence of bytes.

import java.nio.charset.StandardCharsets;

public class GetBytesExample {
    public static void main(String[] args) {
        String str = "javaguides";
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        for (byte b : bytes) {
            System.out.print(b + " ");
        }
        // Output: 106 97 118 97 103 117 105 100 101 115
    }
}

getChars()

Copies characters from this string into the destination character array.

public class GetCharsExample {
    public static void main(String[] args) {
        String str = "This is a demo of the getChars method.";
        char[] buf = new char[10];
        str.getChars(10, 20, buf, 0);
        System.out.println(buf); // Output: demo of th
    }
}

hashCode()

Returns a hash code for this string.

public class HashCodeExample {
    public static void main(String[] args) {
        String str = "javaguides";
        int hashCode = str.hashCode();
        System.out.println("Hash code: " + hashCode); // Output: -138203751
    }
}

indexOf()

Returns the index within this string of the first occurrence of the specified character or substring.

public class IndexOfExample {
    public static void main(String[] args) {
        String str = "javaguides";
        int index = str.indexOf("guides");
        System.out.println("Index of 'guides': " + index); // Output: 4
    }
}

intern()

Returns a canonical representation for the string object.

public class InternExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String newStr = new String("javaguides");
        System.out.println(newStr.intern() == str); // Output: true
    }
}

lastIndexOf()

Returns the index within this

string of the last occurrence of the specified character or substring.

public class LastIndexOfExample {
    public static void main(String[] args) {
        String str = "javaguides";
        int lastIndex = str.lastIndexOf('g');
        System.out.println("Last index of 'g': " + lastIndex); // Output: 4
    }
}

length()

Returns the length of this string.

public class LengthExample {
    public static void main(String[] args) {
        String str = "Java Guides";
        int length = str.length();
        System.out.println("Length: " + length); // Output: 11
    }
}

matches()

Tells whether or not this string matches the given regular expression.

public class MatchesExample {
    public static void main(String[] args) {
        String str = "javaguides";
        boolean matches = str.matches(".*guides.*");
        System.out.println("Matches regex '.*guides.*': " + matches); // Output: true
    }
}

offsetByCodePoints()

Returns the index within this String that is offset from the given index by codePointOffset code points.

public class OffsetByCodePointsExample {
    public static void main(String[] args) {
        String str = "javaguides";
        int index = str.offsetByCodePoints(0, 4);
        System.out.println("Index offset by 4 code points from index 0: " + index); // Output: 4
    }
}

regionMatches()

Tests if two string regions are equal.

public class RegionMatchesExample {
    public static void main(String[] args) {
        String str1 = "javaguides";
        String str2 = "guides";
        boolean result = str1.regionMatches(4, str2, 0, 6);
        System.out.println("Region matches: " + result); // Output: true
    }
}

replace()

Replaces each occurrence of the specified character or substring.

public class ReplaceExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String newStr = str.replace('a', 'o');
        System.out.println("Replaced 'a' with 'o': " + newStr); // Output: jovoguides
    }
}

replaceAll()

Replaces each substring of this string that matches the given regular expression with the given replacement.

public class ReplaceAllExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String newStr = str.replaceAll("[aeiou]", "*");
        System.out.println("Replaced vowels with '*': " + newStr); // Output: j*v*gu*d*s
    }
}

replaceFirst()

Replaces the first substring of this string that matches the given regular expression with the given replacement.

public class ReplaceFirstExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String newStr = str.replaceFirst("[aeiou]", "*");
        System.out.println("Replaced first vowel with '*': " + newStr); // Output: j*vaguides
    }
}

split()

Splits this string around matches of the given regular expression.

public class SplitExample {
    public static void main(String[] args) {
        String str = "java,guides,net";
        String[] parts = str.split(",");
        for (String part : parts) {
            System.out.println(part);
        }
        // Output:
        // java
        // guides
        // net
    }
}

startsWith()

Tests if this string starts with the specified prefix.

public class StartsWithExample {
    public static void main(String[] args) {
        String str = "javaguides";
        boolean result = str.startsWith("java");
        System.out.println("Starts with 'java': " + result); // Output: true
    }
}

subSequence()

Returns a character sequence that is a subsequence of this sequence.

public class SubSequenceExample {
    public static void main(String[] args) {
        String str = "javaguides";
        CharSequence subSeq = str.subSequence(0, 4);
        System.out.println("Subsequence: " + subSeq); // Output: java
    }
}

substring()

Returns a new string that is a substring of this string.

public class SubstringExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String subStr = str.substring(4);
        System.out.println("Substring from index 4: " + subStr); // Output: guides
    }
}

toCharArray()

Converts this string to a new character array.

public class ToCharArrayExample {
    public static void main(String[] args) {
        String str = "javaguides";
        char[] charArray = str.toCharArray();
        for (char c : charArray) {
            System.out.print(c + " ");
        }
        // Output: j a v a g u i d e s
    }
}

toLowerCase()

Converts all of the characters in this string to lowercase using the rules of the default locale.

public class ToLowerCaseExample {
    public static void main(String[] args) {
        String str = "JAVAGUIDES";
        String lowerStr = str.toLowerCase();
        System.out.println("Lowercase: " + lowerStr); // Output: javaguides
    }
}

toUpperCase()

Converts all of the characters in this string to uppercase using the rules of the default locale.

public class ToUpperCaseExample {
    public static void main(String[] args) {
        String str = "javaguides";
        String upperStr = str.toUpperCase();
        System.out.println("Uppercase: " + upperStr); // Output: JAVAGUIDES
    }
}

trim()

Returns a string whose value is this string, with any leading and trailing whitespace removed.

public class TrimExample {
    public static void main(String[] args) {
        String str = "   javaguides   ";
        String trimmedStr = str.trim();
        System.out.println("Trimmed: '" + trimmedStr + "'"); // Output: 'javaguides'
    }
}

valueOf()

Converts different types of values into a string.

public class ValueOfExample {
    public static void main(String[] args) {
        boolean b = true;
        char c = 'A';
        int i = 123;
        long l = 12345L;
        float f = 1.23f;
        double d = 1.234567;

        System.out.println(String.valueOf(b)); // Output: true
        System.out.println(String.valueOf(c)); // Output: A
        System.out.println(String.valueOf(i)); // Output: 123
        System.out.println(String.valueOf(l)); // Output: 12345
        System.out.println(String.valueOf(f)); // Output: 1.23
        System.out.println(String.valueOf(d)); // Output: 1.234567
    }
}

strip()

Removes leading and trailing white space according to the Unicode definition of whitespace.

public class StripExample {
    public static void main(String[] args) {
        String str = "   javaguides   ";
        String strippedStr = str.strip();
        System.out.println("Stripped: '" + strippedStr + "'"); // Output: 'javaguides'
    }
}

stripLeading()

Removes leading whitespace.

public class StripLeadingExample {
    public static void main(String[] args) {
        String str = "   javaguides";
        String strippedLeadingStr = str.stripLeading();
        System.out.println("Leading stripped: '" + strippedLeadingStr + "'"); // Output: 'javaguides'
    }
}

stripTrailing()

Removes trailing whitespace.

public class StripTrailingExample {
    public static void main(String[] args) {
        String str = "javaguides   ";
        String strippedTrailingStr = str.stripTrailing();
        System.out.println("Trailing stripped: '" + strippedTrailingStr + "'"); // Output: 'javaguides'
    }
}

isBlank()

Checks if the string is empty or contains only whitespace characters.

public class IsBlankExample {
    public static void main(String[] args) {
        String str = "   ";
        boolean isBlank = str.isBlank();
        System.out.println("Is blank: " + isBlank); // Output: true
    }
}

lines()

Returns a stream of lines extracted from the string, separated by line terminators.

public class LinesExample {
    public static void main(String[] args) {
        String str = "javaguides\nJava 11";
        str.lines().forEach(System.out::println);
        // Output:
        // javaguides
        // Java 11
    }
}

repeat()

Repeats the string the specified number of times.

public class RepeatExample {
    public static void main(String[] args) {
        String str = "javaguides ";
        String repeatedStr = str.repeat(3);
        System.out.println("

Repeated: " + repeatedStr); // Output: javaguides javaguides javaguides
    }
}

indent()

Adjusts the indentation of each line of the string based on the value of n.

public class IndentExample {
    public static void main(String[] args) {
        String str = "Java\n12";
        String indentedStr = str.indent(4);
        System.out.println("Indented:\n" + indentedStr);
        // Output:
        //     Java
        //     12
    }
}

transform()

Applies the provided function to the string.

public class TransformExample {
    public static void main(String[] args) {
        String original = "  java 12  ";
        String transformed = original
                .transform(String::strip)
                .transform(s -> s.concat(" is awesome"))
                .transform(String::toUpperCase);
        System.out.println("Transformed: " + transformed); // Output: JAVA 12 IS AWESOME
    }
}

describeConstable()

Returns an Optional describing the string, suitable for use in constant expression.

import java.util.Optional;

public class DescribeConstableExample {
    public static void main(String[] args) {
        String str = "Java";
        Optional<String> opt = str.describeConstable();
        opt.ifPresent(System.out::println); // Output: Java
    }
}

resolveConstantDesc()

Part of the JVM’s constant API, resolving a String constant description to a String.

import java.lang.invoke.MethodHandles;

public class ResolveConstantDescExample {
    public static void main(String[] args) {
        String str = "Java";
        String resolved = str.resolveConstantDesc(MethodHandles.lookup());
        System.out.println("Resolved: " + resolved); // Output: Java
    }
}

formatted()

Formats the string using the given arguments, similar to String.format().

public class FormattedExample {
    public static void main(String[] args) {
        String template = "Welcome to %s!";
        String result = template.formatted("javaguides");
        System.out.println("Formatted: " + result); // Output: Welcome to javaguides!
    }
}

stripIndent()

Removes incidental white space from the beginning and end of every line in the string.

public class StripIndentExample {
    public static void main(String[] args) {
        String textBlock = """
               javaguides
               Java 15
            """;
        String result = textBlock.stripIndent();
        System.out.println("Stripped Indent:\n" + result);
        // Output:
        // javaguides
        // Java 15
    }
}

translateEscapes()

Translates escape sequences like \n, \t, etc., in the string as if in a string literal.

public class TranslateEscapesExample {
    public static void main(String[] args) {
        String str = "javaguides\\nJava 15";
        String result = str.translateEscapes();
        System.out.println("Translated Escapes:\n" + result);
        // Output:
        // javaguides
        // Java 15
    }
}

Conclusion

The String class in Java provides a comprehensive set of methods for creating, manipulating, and handling strings. By understanding and utilizing these methods, you can efficiently manage string operations in your Java applications. This guide covers a broad range of methods introduced up to Java 21, demonstrating how to use each with simple, beginner-friendly examples.

Leave a Comment

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

Scroll to Top