JavaStrings in Java

String Methods in Java

Learn commonly used Java String methods such as length(), charAt(), substring(), equals(), compareTo(), and case conversion methods with examples.

String Methods in JavaLink to this section

Java provides a rich set of built-in methods in the String class to perform operations like searching, comparison, modification, and transformation of text.

Since strings are immutable, all string methods return a new String object instead of modifying the existing one.

length() MethodLink to this section

The length() method returns the number of characters present in a string.

charAt() MethodLink to this section

The charAt() method returns the character at a specific index. Indexing starts from 0.

warning

Accessing an index outside the string length will cause StringIndexOutOfBoundsException.

substring() MethodLink to this section

The substring() method extracts a part of the string.

note

The ending index is excluded.

equals() and equalsIgnoreCase()Link to this section

These methods compare string content.

toUpperCase() and toLowerCase()Link to this section

These methods convert the string to uppercase or lowercase.

tip

These methods are useful when performing case-insensitive comparisons.

trim() MethodLink to this section

The trim() method removes leading and trailing spaces from a string.

note

It does not remove spaces between words.
String Methods in Java
Question 1 of 5

Which method returns the number of characters in a string?

String Methods in Java

medium
  1. Write a program to count the number of characters in a user-entered string.
  2. Extract the first five characters from a given string.
  3. Check whether two strings are equal without considering case.
  4. Remove extra spaces from a sentence entered by the user.
  5. Convert a string into both uppercase and lowercase formats and display them.