4

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...

Jon Seigel
  • 12,035
  • 8
  • 56
  • 92
allaire
  • 5,965
  • 3
  • 39
  • 56

4 Answers4

11

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.

mmmmmm
  • 31,464
  • 27
  • 87
  • 113
  • 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? – mmmmmm Feb 24 '10 at 17:24
  • 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 Feb 24 '10 at 17:26
  • 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 – mmmmmm Feb 24 '10 at 17:34
  • `String` does overload `+`—the one and only case of operator overloading in Java. – Taymon Jun 01 '12 at 23:09
1

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
  • 66,311
  • 27
  • 138
  • 208
0

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++

GuruKulki
  • 25,118
  • 47
  • 138
  • 197
-1

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
  • 1,187
  • 1
  • 9
  • 22