Creating strings is one of the easiest things you can do in Java, and there are four main ways to do so.
In the examples below, let’s assume you want to create a string of the word “testing,” using “qa” as the reference word.
Way #1:
String qa;
qa = “testing”;
First, you’re declaring the String type variable, then you’re assigning text to the variable.
Way #2 – String Literal:
String qa = “testing”;
This way, known as “string literal,” is perhaps the most common way of creating a string, and usually the quickest — it’s all done in one line, with the least amount of text.
It’s also less memory-intensive, since it’s stored in what’s called “String Constant Pool.”
Way #3 – String Object:
String qa = new String(“testing”);
As you can see, this way (“string object”) is similar to the second way shown above, but requires extra text. This type of string is stored in Heap Memory.
Way #4 – From Array:
char mylist[] = {‘t’, ‘e’, ‘s’, ‘t’, ‘i’, ‘n’, ‘g’};
String qa = new String(mylist);
First, you’re creating an array of each letter in the word “testing.”
Then, you’re converting that array into one string, which consists of the word “testing.”