Using the String ClassIn Java, you create strings by creating an instance of the String class. This String object can be created implicitly or explicitly depending on how the string is being used in the program. To create a string implicitly, you just place a string literal in your program, and Java automatically creates a String object for the string. This is because, even internally, Java uses String objects to represent string literals. Look at this line, for example: String fullName = new String( "Mr. John Doe" ); Java implicitly creates a String object for the string literal "Mr. John Doe". Every time you refer to a string this way in a Java program, you're creating a String object. The other way to create a String object is to explicitly instantiate an object of the String class. The String class has nine constructors, so there are plenty of ways to explicitly create a String object, the most obvious way being this: String str = new String("This is a string"); You can also declare a String object and then set its value later in the program, like this: String str = null; str = "This is a string"; Finally, any of the following lines creates a null string: String str = new String(); String str = ""; Caution There's a big difference between a null String object reference and a null string. When you declare a String object with a line such as String str = null, you are declaring an object of the String class that has not yet been instantiated . That is, there is not yet a String object associated with the variable str. When you create a String object with a line such as String str = "", you are creating a fully instantiated String object whose string contains no characters (has a string length of zero). This is called a null or an empty string. Although the preceding examples are the most common ways of explicitly creating String objects, the String class offers several alternatives. The nine constructors in the String class look like this: public String() public String(byte[] bytes) public String(byte[] bytes, int offset, int length) public String(byte[] bytes, int offset, int length, String enc) public String(byte[] bytes, String enc) public String(char[] value) public String(char[] value, int offset, int count) public String(String value) public String (StringBuffer buffer) These constructors create, respectively, the following:
|