DEV Community

Atharva Siddhabhatti
Atharva Siddhabhatti

Posted on • Updated on

Strings in Java

As other languages, String in java is also a sequence of characters. But java does not implement string as an array of character rather it considers it as a complete object of type string.

How to create a string object using new keyword and literals

There are two ways in which we can create a string object, by using new keyword or by using literals. Literal representation means literally representing the value of it like integer, string. Below code represents how we can create a string using new keyword.

String a = new String();
Enter fullscreen mode Exit fullscreen mode

As we know, new keyword is used to create the instance of that class. Above we have created an instance ‘a’ of a type string with no characters. To create a string with a value in it then you can do that like this.

char name[] = {‘x’,’y’,’z’}
String a = new String(chars);
Enter fullscreen mode Exit fullscreen mode

Above we have created an character array name[] with values ‘x’, ‘y’, ‘z’ and then we allocated that complete array to the string ‘a’. We have used the constructor of String class to initialize the value of the string.

As we have seen above, it is little confusing and lengthy to create a string using new keyword. But there is a really easy way to that and this is where the literals come to save us.

String s = “xyz”;
Enter fullscreen mode Exit fullscreen mode

This is how we create the string in java using literals. For every string literal in program, Java automatically constructs a String object with the initial value provided to it. You can use a string literal any place in you program to create a string object of it.

String Example

Let’s write a simple hello world program.

public class HelloWorld {
    public static void main(String args[]) {

        String s1 = new String("Hello World using new keyword"); // Using new keyword
        String s2 = "Hello World using literals";

        System.out.println(s1);
        System.out.println(s2);
}
}
Enter fullscreen mode Exit fullscreen mode

Run Code From here:- CLICK HERE

Top comments (0)