there is my question that normally in java we create object with new operator but when we want to use String and String is also a class then we declare object without new operator why plz answer my question

Recommended Answers

All 3 Replies

you didn't ask a question.
String is immutable, but it's soo often used, that having complete new instances in the memory would be a huge drain on the resources of your system.

in your memory there is also a String pool, used to group all instances of a String currently used.

if you code it like:

String a = "hello";

your code will not automatically create a new instance of "hello", but it will first check the String pool, to see if a String with that value is already present.

if it is, a will reference to that String, otherwise a new String is created in the pool.

if you write:

String a = new String("hello");

whether there's already a String instance of "hello" in the pool or not, a new instance will be created and added to the String pool, and a will reference this new instance

Because you want to make many Strings in a normal program, Java has special syntax to make it easy, eg.

String name = "Joe";

without that you would have to say something like

char[] letters = {'J', 'o', 'e'};
String name = new String(letters);

So it is in the language to make your life easy. That's all.

see this post
they give good explanation Click Here
its easy to understand.

:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.