thisisbhavin
thisisbhavin

Reputation: 364

What was the need for string to be object in java

I understood that Strings in java are not normal variables like int or float, it is object but my question is why was it necessary to do this? why string could not be normal variable like sequence of characters? what was that thing that made java designers to make string as object?

Upvotes: 3

Views: 1072

Answers (2)

Henry
Henry

Reputation: 43728

The main difference between String and other primitive types (like int) is that its values need variable amount of memory depending on the string length. This makes it difficult to keep them on the stack.

On the other hand we have the string concatenation operator s1 + s2 and string literals "abc", which makes it different from any other object.

Upvotes: 4

Allan
Allan

Reputation: 12438

I would say that there are several reasons that are close to the ones for which wrappers does exist for int/byte/double/... in Java:

  • To allow null value
  • To include it in Collection
  • To have access to the power of generic and polymorphism as an Object along with other Objects
  • To have all the wonderful methods of the class String to manipulate Strings objects
  • To have the String pool working and saving memory (would be difficult if Strings where on the stack and not in the heap)
  • etc.

Links:

Upvotes: 4

Related Questions