Creating Strings


Creating Strings

🙋 Need help? Ask an expert now!

There are two distinct ways to create a String: use double-quotation marks or create a new object. Either put text on the same line in double quotation marks as if it was primitive datatype: String stringName = "hi"; or initialize them like this: String stringName = new String("hi");. Take a look below for examples on how we can initialize a String.
package exlcode;

public class StringsExample {

  public static String exampleVariableOne = new String("Hello World!");
  // the next two statements create an empty String
  public static String exampleVariableTwo = new String();
  public static String exampleVariableThree = "";
  public static String exampleVariableFour = "Java";

  public static void main(String[] args) {

To create a new object, we use the Java reserved word new because String is a class within the java.lang package. However, Java has made the process of importing easier for programmers. As you see above, you can initialize the String without having to type out new. Ultimately, it is up to you to decide which method of creating a String works best for you.

Remember, it is possible to create an empty String by either leaving the parenthesis blank or omitting characters on the inside of the double-quotation marks.

Edit Me on GitHub!

Application Question

Which statement below correctly declares and initializes the String value varOne?