Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. String.length() / charAt()

String.length() / charAt()

Methods for getting the length of a string or retrieving a character at a specified position. Java strings are managed in UTF-16, so use codePointAt() to handle surrogate pairs (such as emoji) correctly.

Syntax

// Returns the number of characters in the string.
string.length();

// Returns the character at the specified position (0-based index).
string.charAt(int index);

// Returns the Unicode code point at the specified position.
string.codePointAt(int index);

Method List

MethodDescription
length()Returns the number of characters in the string as an integer. Returns 0 for an empty string.
charAt(int index)Returns the character at the specified index as a char type. The index is 0-based.
codePointAt(int index)Returns the Unicode code point at the specified index as an int type. Supports surrogate pairs.

Sample Code

// Get the length of a string.
String str = "Hello";
System.out.println(str.length()); // Outputs: 5

// Get the length of a Japanese string.
String name = "山田太郎";
System.out.println(name.length()); // Outputs: 4

// Get the character at a specific position.
String word = "Java";
char c = word.charAt(0);
System.out.println(c); // Outputs: J

// Loop through a string one character at a time.
String text = "abc";
for (int i = 0; i < text.length(); i++) {
    System.out.println(text.charAt(i)); // Outputs: a, b, c in order
}

// Get the code point of a character.
String emoji = "😊abc";
System.out.println(emoji.codePointAt(0)); // Outputs the emoji's code point: 128522

Notes

length() is one of the most commonly used string methods in Java and returns the number of characters in a string. Passing a negative index or an index greater than or equal to the string length throws a StringIndexOutOfBoundsException, so always check the range beforehand.

charAt() returns the character at the specified position as a char type. Because char represents a single UTF-16 code unit, use codePointAt() to correctly handle surrogate pair characters such as emoji.

To extract a portion of a string, use substring(). To search within a string, use indexOf() / contains().

If you find any errors or copyright issues, please .