Multiple choice

Which of the following statements is preferred to create a string "Welcome to Java Programming"?

  1. String str = “Welcome to Java Programming”

  2. String str = new String( “Welcome to Java Programming” )

  3. String str; str = “Welcome to Java Programming”

  4. String str; str = new String (“Welcome to Java Programming” )

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

In Java, string literals are preferred and most commonly used to create string objects directly, utilizing string pooling efficiently. While the new keyword creates a new object in the heap explicitly, string literal assignment is the standard idiomatic practice.