Java – Initialize String
To initialize a string in Java, you can use String class, double quotes (String literal), String.valueOf() method, or StringBuilder class.
1. Initialize a string using String class in Java
You can initialize a string in Java using String class. Create a new String class object and you may pass the required string literal as argument to the String constructor.
String myString = new String("Hello World");
This statement initializes myString variable with a string value of "Hello World"
.
Now, let us write a Java program, to initialize a string with the value "Hello World"
using String class and print it to output.
Java Program
public class Main {
public static void main(String[] args) {
String myString = new String("Hello World");
System.out.println(myString);
}
}
Output
Hello World
2. Initialize a string using double quotes in Java
You can initialize a string in Java using double quotes. Enclose the required sequence of characters within double quotes, and this string literal is ready to be assigned to a string variable.
String myString = "Hello World";
This statement initializes myString variable with a string value of "Hello World"
.
Now, let us write a Java program, to initialize a string with the value "Hello World"
using double quotes and print it to output.
Java Program
public class Main {
public static void main(String[] args) {
String myString = "Hello World";
System.out.println(myString);
}
}
Output
Hello World
3. Initialize a string using String.valueOf() method in Java
You can initialize a string in Java using String.valueOf() method. This method is usually used to create a string from values of other datatypes.
For example, in the following statement, a string value is created from an integer value.
String myString = String.valueOf(123456);
This statement initializes myString variable with a string value of "123456"
.
Now, let us write a Java program, to initialize a string with the value "123456"
from an integer value, using String.valueOf() method, and print it to output.
Java Program
public class Main {
public static void main(String[] args) {
String myString = String.valueOf(123456);
System.out.println(myString);
}
}
Output
Hello World
Similarly, you can initialize a string value from other datatypes like character, floating point, object, etc.
Conclusion
In this Java String tutorial, we have seen how to initialize a string value in different ways, with examples.