A String is a collection of letters/alphabets. It can be a word or a sentence.
The Data Type for String is String.
When Java finds data inside Double Quotes (""). It creates a String type variable for that value.
var x = "Hello World";
var is independent of data type. i.e. The above variable x can accept a value of any data type.
public class MyApplication {
public static void main(String[] args) {
var x = "Hello World";
System.out.println(x);
}
}
And that's all! You have a String in place.
Well! There are other ways using which you can create a String.
public class MyApplication {
public static void main(String[] args) {
String x = "Hello World";
System.out.println(x);
}
}
So, in the above code, we have declared a variable x of String type.
String x = "Hello World";
So that it would not accept any values other than a String.
Also one more advantage of declaring using a String type is that you can assign the value to the String variable later.
Let us understand with the below code.
public class MyApplication {
public static void main(String[] args) {
String x;
x = "Hello World";
System.out.println(x);
}
}
Just note that we have not initialised the variable x. We have just declared it.
String x;
So that an empty variable x would be created that would only hold a String.

Then in the next line, we have assigned the value Hello World to the variable x.
x = "Hello World";

Well! We have declared a String type variable and assigned it later.
But the below code won't work, if we do not specify a data type.
public class MyApplication
{
public static void main(String[] args)
{
var x;
x = "Hello World";
System.out.println(x);
}
}
And if you take a look at the below output, the above code didn't work because we haven't specified any data type.
var x;
length() method is used to return the length of a String.
public class MyApplication
{
public static void main(String[] args)
{
String x = "Hello";
System.out.println("The length of the String is : "+x.length());
}
}