views:

232

answers:

5
+3  Q: 

= operator in java

can somebody explain me why it's possible to do:

String s = "foo";

how is this possible without operator overloading (in that case the "=")

I'm from a C++ background so that explains...

A: 

It is an assignment operator in java which is used to assign the value to the declared type, where no operator overloading is required. Even in c++

GK
A: 

It's not as easy as this, but think of all objects as pointers.

Pablo Rodriguez
+10  A: 

In this case there is no overloading. The java piece that differs from C++ is the definition of "" - The java compiler converts anything in "" into a java.lang.string and so is a simple assignment in your example. In C++ the compiler converts "" into a char const * and so needs to have a conversion from char const* to std::string.

Mark
Thanks! got it :)
all-R
What about the + operator?
Samuel Carrijo
Samuel what about it - the question is in effect why is there no implicit or explicit conversion as there woud be in C++ for String s = "foo"; - how would + come in here?
Mark
The compiler converts the series of concatentations into a StringBuffer instantiation followed by append calls with the String objects as mentioned in this answer. http://java.sun.com/developer/JDCTechTips/2002/tt0305.html
basszero
Ah I see - string concatination is also detailed in the Java language docs http://java.sun.com/javase/6/docs/api/java/lang/String.html
Mark
+1  A: 

This assigns a simple literal of type String to s

In Java Strings are immutable, if you need to define a constant value you would use the final keyword.

stacker
Thanks I'll take a look :)
all-R
A: 

The API says:

"Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";

"is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
David