Ways to create the string object in Java
There are various ways you can create a String Object in Java:
Using String literals
String literals are created by enclosing a sequence of characters within double quotation marks.
In this case, the Java compiler automatically creates a String object representing the literal "Hello, World!".
Using the new keyword
String objects can also be created explicitly using the new keyword followed by the String constructor.
This approach creates a new String object, regardless of whether an identical string already exists in the string pool.
Converting other data types to String
Java provides methods for converting other data types to String using built-in functions like valueOf() or toString().
In this case, the valueOf() method converts the integer value 123 into a String object.
Using StringBuilder or StringBuffer
The StringBuilder and StringBuffer classes provide flexible ways to construct and manipulate strings. These classes offer various methods for appending, modifying, or manipulating characters, ultimately resulting in a String object.
In this case, a StringBuilder object is used to construct the string "Hello World", which is then converted to a String object using the toString() method.
Each approach has its own use cases and advantages, allowing developers to choose the most suitable method based on their specific requirements.