Creating an object of the String class

We create an object of the String class as shown in the following line of code:

        String ab=new String();

Now, to create a hello string, you could simply pass an argument into the String class, as follows:

        String ab=new String("hello");

The ab object can now perform all the string manipulations on this hello string.

Let's create another string, called b, which also equals to hello, as follows:

        String a=new String("hello");
String b=new String("hello");

Here, though, there is already one hello string created with the a object, and when the Java compiler comes to the b object, it will still create one more duplicate hello string and assign it to b, because here we are explicitly forcing it to create an object for this class. Although there is a duplicate already present, it will still create an object for this string; however, in defining a String literal, if the object is already present in the String pool, it will not create it—instead, it directly refers it to the already created object.

So that's the basic difference between creating a string with the String literal object and separately creating an object with the String class. Ultimately, both support String methods, but there is some difference between the two methods when it comes to defining a string.

What is the difference between these two methods that we just learned? Both strings have access to the hello string, but you can see that there is some difference between them. If you declare the string in the literal fashion at the backend, then Java assigns hello to the a variable. So this is a more direct way of creating a string, rather than using the object creation method.

In most of our regular Java working experience, we would prefer to use the String literal. We just state that a equals hello, and that's it. It's just like how you define integers. But String is a class, and at the backend, it creates a separate object for this hello string, whereas an integer is just a reference data type, so nothing will happen at its backend.

Let's see what manipulations we can apply to this hello string with the object we created.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.246.193