Basic Properties of a String

Learn the basic properties of a string in Java.

Length of a string

The length of a string is the total number of characters present in that string. For example, the length of the string “I love Java.” is 1212.

You must be thinking that it’s hectic to count every character to find the string’s length. The example above was not even long. What if we get a string with a long length, maybe with 100 characters in it? Will we have to count it character by character?

Don’t worry! There’s no need for us to count. Let the computer do it! Let’s write a program in Java that will calculate the length of a string.

Press + to interact
class StringLength
{
public static void main(String args[])
{
String s = "I love Java.";
System.out.println(s.length()); // Accessing length with length()
}
}

Woah! What just happened? The computer gave the result within only 2 seconds. But how?

Look at line 6. We are calling the length() method (of the String class) on s, which returns the length of string s.

Indexing

The numerical representation of the character’s position in a string is called an index. For a string of length n:

  • The index of the first character is always 00
...