Constructing a String

Edit on Github instead

To make a string, you can enclose text on the same line in double quotation marks (" and ") as if they were a primitive:

String favorite = "Computer Science";

Or, you can initialize them as you would an object:

String favorite = new String("Computer Science");

Strings can be empty. Here's two ways to define an empty string:

String empty = "";
String alsoEmpty = new String();

String objects are immutable – there's no way to change them once they've been made – but their references can be reassigned:

String favorite = "Computer Science";
// favorite is "Computer Science"
favorite = "Art History";
// favorite is now "Art History"

The third line reassigns the favorite variable from "Computer Science" to "Art History".

Suggest changes

Related links

URL Topic Source