Java String length (String size)

Question: How do I determine the Java String length, i.e., the length of a String in Java?

Answer: Just use the length method of the Java String class.

Here's the source code for a short but complete example that demonstrates how to determine the Java String length for a String appropriately named string:

/**
 * Determine the Java String length, i.e.,
 * the length of a String in Java.
 * @author alvin alexander, devdaily.com
 *
 */
public class JavaStringLength
{

  public static void main(String[] args)
  {
    String string = "Four score and seven years ago ...";
    int length = string.length();
    
    System.out.format("The Java String length is: %d", length);
  }

}

The String length is retrieved in this line:

int length = string.length();

FWIW, you can also shorten this Java String length example by combining those last two lines, like this:

String string = "Four score and seven years ago ...";
System.out.format("The Java String length is: %d", string.length());

The approach really depends on whether you need/prefer to use a length variable in your code, or not.

For the record, either of these two String length approaches will print the following output:

The Java String length is: 34