First, let's clear up a few things with the small sample you provided. StringBuilder is a class. You can declare a variable to be of type StringBuilder. That is to say the variable can hold/refer to StringBuilder objects. The variable must have a valid identifier (a.k.a. name).
StringBuilder my_string_builder; // declares a variable named my_string_builder which can hold StringBuilder objects
You can create StringBuilder objects using the StringBuilder's constructor. A constructor is a special method inside of StringBuilder with the same name as the class, StringBuilder. To call a constructor you must use the new
keyword. Some classes can have more than one constructor defined. As you indicated, there's a constructor which takes a String object and creates a StringBuilder object initialized with the String's data.
new StringBuilder("a test string");
Let's put the two parts together and create a StringBuilder object and assign it to a variable so we can use that variable to manipulate that StringBuilder object.
StringBuilder my_string_builder = new StringBuilder("a test string");
You don't need to provide a String literal, you just need to give it a valid String object.
String test_string = "this is a string";
StringBuilder my_string_builder = new StringBuilder(test_string);
Now that bit out of the way, why do you think you need a StringBuilder object? What does the StringBuilder object give you? I would suggest reading the StringBuilder JavaDoc
to find out what a StringBuilder is.
The very first sentence describes exactly a StringBuilder is.
A mutable sequence of characters.
mutable means you can change it. Strings in Java, on the other hand, are immutable. That means once you have a String object it will be the same from the time it's created to the time it's destroyed. Note that I was careful to say that a String object
is immutable. String variables
can be changed to refer to other Strings if they're not declared with the final
final String str1 = "a fine day";
String str2 = "Java programming";
str1 = str2; // compile error, the variable str1 can't be made to refer to a different String object.
str2 = str1; // perfectly fine, str2 can refer to the same String object str1 refers to.
So back to the original question of why do you need a StringBuilder object, and why isn't a String object sufficient?
To answer this question think about what steps you have to take in order to figure out if the password inputted is valid. How would you (using a piece of paper and a pencil) figure out if the password contains at least one letter and one number.