String Handling Methods Example

Java String Methods with Examples: charAt, compareTo, indexOf, and More (2026)

Java String Methods with Examples: charAt, compareTo, indexOf, and More

The String class is the most used class in Java. Every program touches it. This guide walks through the String methods you will actually use, with code and output for each one. No fluff. Just the method, what it does, and what it prints.

1. char c = charAt(int index)

Returns the character at the specified index. Indexing starts at 0.

public class StringMethods {

    public static void main(String[] args) {
        String name = "deep singh";
        char c = name.charAt(0);
        System.out.println(c);
    }
}

Result: d

2. int c = codePointAt(int index)

Returns the Unicode code point of the character at the specified index.

public class StringMethods {

    public static void main(String[] args) {
        String name = "deep singh";
        int c = name.codePointAt(0);
        System.out.println(c);
    }
}

Result: 100

3. int c = codePointBefore(int index)

Returns the Unicode code point of the character before the specified index.

public class StringMethods {

    public static void main(String[] args) {
        String name = "deep singh";
        int c = name.codePointBefore(1);
        System.out.println(c);
    }
}

Result: 100

Note: If you pass an index that does not exist, you get a StringIndexOutOfBoundsException.

4. int c = codePointCount(int fromIndex, int toIndex)

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

public class StringMethods {

    public static void main(String[] args) {
        String name = "deep singh";
        int c = name.codePointCount(0, 3);
        System.out.println(c);
    }
}

Result: 3

5. int c = compareTo(String anotherString)

Compares two strings lexicographically. Returns a negative number if the first string is smaller, a positive number if larger, and 0 if equal.

public class StringMethods {
    public static void main(String[] args) {
        String a = "a";
        String b = "b";

        // a is smaller than b, so result is negative
        int c1 = a.compareTo(b);

        // b is greater than a, so result is positive
        int c2 = b.compareTo(a);

        // both are equal, so result is 0
        int c3 = a.compareTo(a);

        System.out.println(c1 + "," + c2 + "," + c3);
    }
}

Result: -1, 1, 0

6. int c = compareToIgnoreCase(String str)

Compares two strings lexicographically, ignoring case.

public class StringMethods {

    public static void main(String[] args) {
        String a = "a";
        String b = "B";

        int c1 = a.compareToIgnoreCase(b);
        int c2 = b.compareToIgnoreCase(a);
        int c3 = a.compareToIgnoreCase(a);

        System.out.println(c1 + "," + c2 + "," + c3);
    }
}

Result: -1, 1, 0

7. String data = concat(String str)

Appends the given string to the end of this string and returns a new string. The original string is not modified.

public class StringMethods {

    public static void main(String[] args) {
        String a = "Deep";
        String b = "Singh";
        String t = a.concat(b);
        System.out.println(a);
        System.out.println(t);
    }
}

Result:
Deep
DeepSingh

8. boolean data = contains(CharSequence s)

Checks whether the string contains the given sequence of characters.

import java.io.Serializable;

public class StringMethods {

    public static void main(String[] args) {
        String a = "hello i am a deep singh";
        CharSequence cs = "deep";
        System.out.println(a.contains(cs));
        System.out.println(a.contains("am"));

        Serializable sl = "hello";
        // contains() does not accept Serializable, so convert to String first
        System.out.println(a.contains(sl.toString()));
    }
}

Result:
true
true
true

9. boolean data = contentEquals(CharSequence cs) or contentEquals(StringBuffer sb)

Checks whether the string has the exact same sequence of characters as the given argument. Overloaded for CharSequence and StringBuffer.

JDK 1.4 added contentEquals(StringBuffer). JDK 1.5 added contentEquals(CharSequence).

public class StringMethods {

    public static void main(String[] args) {
        String a = "deep singh";
        CharSequence s = "deep singh";
        StringBuffer sb = new StringBuffer("deep singh");
        System.out.println(a.contentEquals(s));
        System.out.println(a.contentEquals(sb));
    }
}

Result:
true
true

10. String data = copyValueOf(char[] chars) or copyValueOf(char[] chars, int startIndex, int length)

Copies a char array into a String. This is a static method, so you call it with the class name.

public class StringMethods {

    public static void main(String[] args) {
        char[] chars = { 'd', 'e', 'e', 'p', ' ', 's', 'i', 'n', 'g', 'h' };
        String name = String.copyValueOf(chars);
        System.out.println(name);

        String anotherName = String.copyValueOf(chars, 0, chars.length);
        System.out.println(anotherName);
    }
}

Result:
deep singh
deep singh

11. boolean data = endsWith(String suffix)

Checks whether the string ends with the given suffix.

public class StringMethods {

    public static void main(String[] args) {
        String name = "This is deep singh";
        boolean check = name.endsWith("h");
        System.out.println(check);
    }
}

Result: true

12. boolean data = equals(Object obj)

Compares two strings for exact equality, including case.

public class StringMethods {

    public static void main(String[] args) {
        String name = "hello";
        boolean check = name.equals("hello");
        System.out.println(check);
    }
}

Result: true

13. boolean data = equalsIgnoreCase(String str)

Compares two strings for equality, ignoring case.

public class StringMethods {

    public static void main(String[] args) {
        String name = "hello";
        boolean check = name.equalsIgnoreCase("Hello");
        System.out.println(check);
    }
}

Result: true

14. String data = format(String format, Object... args) or format(Locale l, String format, Object... args)

Formats a string using the given format specifier and arguments. This is a static method.

public class StringMethods {

    public static void main(String[] args) {
        // hexadecimal float
        System.out.println(String.format("%a", 3.14));

        // boolean
        System.out.println(String.format("%b", true));

        // character
        System.out.println(String.format("%c", 'a'));

        // decimal integer
        System.out.println(String.format("%d", 123457));

        // scientific notation
        System.out.println(String.format("%e", 49.000000));

        // float
        System.out.println(String.format("%f", 1.234574));

        // hash code
        System.out.println(String.format("%h", 123457));

        // newline
        System.out.println(String.format("%n", 123457));

        // octal
        System.out.println(String.format("%o", 123457));

        // string
        System.out.println(String.format("%s", "Hello World"));

        System.out.println(String.format("%tA", System.currentTimeMillis()));
        System.out.println(String.format("%tB", System.currentTimeMillis()));
        System.out.println(String.format("%tD", System.currentTimeMillis()));
        System.out.println(String.format("%tT", System.currentTimeMillis()));
        System.out.println(String.format("%tZ", System.currentTimeMillis()));
        System.out.println(String.format("%tY", System.currentTimeMillis()));

        System.out.println(String.format("%ta", System.currentTimeMillis()));
        System.out.println(String.format("%tb", System.currentTimeMillis()));
        System.out.println(String.format("%td", System.currentTimeMillis()));
    }
}

15. byte[] data = getBytes()

Converts the string into a byte array.

public class StringMethods {

    public static void main(String[] args) {
        String name = "hello";
        byte[] bytes = name.getBytes();
        System.out.println(bytes);
    }
}

Result: [B@1db9742

16. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Copies characters from the string into a char array.

public class StringMethods {

    public static void main(String[] args) {
        String name = "hello";
        char[] chars = new char[name.length()];
        name.getChars(0, name.length(), chars, 0);
        for (int i = 0; i < chars.length; i++) {
            System.out.print(chars[i]);
        }
    }
}

Result: hello

17. int position = indexOf(int ch) or indexOf(String str) or indexOf(int ch, int fromIndex) or indexOf(String str, int fromIndex)

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

public class StringMethods {

    public static void main(String[] args) {
        String name = "hi Sir";
        int i = name.indexOf('i');
        System.out.println(i);
        int j = name.indexOf("Sir");
        System.out.println(j);
        int k = name.indexOf('i', 2);
        System.out.println(k);
        int l = name.indexOf("i", 1);
        System.out.println(l);
    }
}

Result: 1 3 4 -1

18. String data = intern()

Returns the string from the string constant pool. If the string is not in the pool, it is added. Useful for saving memory when many identical strings exist.

public class StringMethods {

    public static void main(String[] args) {
        // using new keyword
        String name = new String("deep");

        System.out.println(name);
        System.out.println(name.intern());

        // name is in heap, intern() is in constant pool, so references differ
        System.out.println(name == name.intern());

        // but contents are equal
        System.out.println(name.equals(name.intern()));

        // using literal
        String anotherName = "deep";

        // name points to heap, anotherName points to pool
        System.out.println(anotherName == name);

        // intern() returns the pool reference, which matches anotherName
        System.out.println(anotherName == name.intern());
    }
}

19. boolean status = isEmpty()

Checks whether the string is empty (length 0).

public class StringMethods {

    public static void main(String[] args) {
        String name = "";
        System.out.println(name.isEmpty());
    }
}

Result: true

20. int position = lastIndexOf(int ch) or lastIndexOf(String str) or lastIndexOf(int ch, int fromIndex) or lastIndexOf(String str, int fromIndex)

Returns the position of the last occurrence of a character or substring. Returns -1 if not found.

public class StringMethods {

    public static void main(String[] args) {
        String name = "Deep Singh";
        int i = name.lastIndexOf('e');
        System.out.println(i);
        int j = name.lastIndexOf("e");
        System.out.println(j);
        int k = name.lastIndexOf('e', 3);
        System.out.println(k);
        int l = name.lastIndexOf("e", 3);
        System.out.println(l);
    }
}

Result: 2 2 2 2

Where to go next

You now know the String methods that come up in every Java project. Each one is small, but together they cover most of the text manipulation you will ever do.

If you remember one thing, remember this: String is immutable. Every method that "changes" a string actually returns a new string. The original never changes.

If you want to go deeper, try these next steps:

  • Test the exception behavior. Call charAt(100) and read the message.
  • Compare == and equals() on two strings created with new and two created with literals. The difference will stick.
  • Explore StringBuilder and StringBuffer. They are mutable and much faster when you need to concatenate in a loop.
  • Move on to regular expressions with String.matches(), split(), and replaceAll(). That is where String gets really powerful.

2 comments:

Anany Sharma said...

Best sir best , First time I got full knowledge of string methods

Unknown said...

Outstanding explanation sir... 👌