Java Data Type Tutorial - Java String Create/Length








Creating String Objects

The String class contains many constructors that can be used to create a String object.

The default constructor creates a String object with an empty string as its content.

For example, the following statement creates an empty String object and assigns its reference to the emptyStr variable:

String  emptyStr = new String();

The String class contains a constructor, which takes another String object as an argument.

String str1 = new String();
String str2 = new String(str1); // Passing a  String as  an  argument

Now str1 represents the same sequence of characters as str2. At this point, both str1 and str2 represent an empty string. We can also pass a string literal to this constructor.

String str3 = new String("");
String str4 = new String("Have fun!");

After these two statements are executed, str3 will refer to a String object, which has an empty string as its content, and str4 will refer to a String object, which has "Have fun!" as its content.





Length of a String

The String class contains a length() method that returns the number of characters in the String object.

The return type of the method length() is int. The length of an empty string is zero.

public class Main {
  public static void main(String[] args) {
    String str1 = new String();
    String str2 = new String("Hello");
/* w  w  w  .ja  v a2s.co m*/
    // 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);
  }
}

The code above generates the following result.