Java Reference
In-Depth Information
Length of a String
The String class contains a length() method that returns the number of characters in the String object. Note that
the length() method returns the number of characters in the string, not the number of bytes used by the string. The
return type of the method length() is int . Listing 11-1 demonstrates how to compute the length of a string. The length
of an empty string is zero.
Listing 11-1. Knowing the Length of a String
// StringLength.java
package com.jdojo.string;
public class StringLength {
public static void main (String[] args) {
// Create two string objects
String str1 = new String() ;
String str2 = new String("Hello") ;
// Get the length of str1 and str2
int len1 = str1.length();
int len2 = str2.length();
// Display the length of str1 and str2
System.out.println("Length of \"" + str1 + "\" = " + len1);
System.out.println("Length of \"" + str2 + "\" = " + len2);
}
}
Length of "" = 0
Length of "Hello" = 5
String Literals Are String Objects
All string literals are objects of the String class. The compiler replaces all string literals with a reference to a String
object. Consider the following statement:
String str1 = "Hello";
When this statement is compiled, the compiler encounters the string literal "Hello" , and it creates a String
object with "Hello" as its content. For all practical purposes, a string literal is the same as a String object. Wherever
you can use the reference of a String object, you can also use a String literal. All methods of the String class can be
used with String literals directly. For example, to compute the length of String literals, you can write
int len1 = "".length(); // len1 is equal to 0
int len2 = "Hello".length(); // len2 is equal to 5
 
Search WWH ::




Custom Search