Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does + operator behaves differently with numbers and strings in Java?

Tags:

java

Java does not have concept of operator overloading.

Still + operator behaves as addition operator with numbers and concatenate operator with strings. This is similar to the operator overloading behavior.

So, does Java have operator overloading?

like image 301
Abhishek Jain Avatar asked Jun 02 '10 07:06

Abhishek Jain


People also ask

Is it possible to use operator with operands as a string and a number?

YES! As you've found out, the operator + can mean two different things, string concatenation or numeric addition.

How does == operator behave in case of string?

String comparison is a common scenario of using both == and equals method. Since java. lang. String class override equals method, It returns true if two String object contains same content but == will only return true if two references are pointing to the same object.

How does * Operator behave on string?

Explanation: The * operator can be used to repeat the string for a given number of times. Writing two string literals together also concatenates them like + operator. If we want to concatenate strings in different lines, we can use parentheses.

Which operator is used with integers as well as with string?

The multiplication operator acts as a replication operator when we have one string and one integer as operands.


2 Answers

It's basically operator overloading - just built into the language.

"Java does not have concept of operator overloading" is only true inasmuch developers cannot overload operators.

The language spec can, and strictly speaking, all the arithmetic operators are overloaded to handle calculations that involve more than one numerical type. And even there, it sometimes creates confusion (such as having to cast one operand to double if you want a divsion of int values to yield fractional results).

like image 124
Michael Borgwardt Avatar answered Oct 07 '22 17:10

Michael Borgwardt


Does the Java language overload some operators?

YES! As you've found out, the operator + can mean two different things, string concatenation or numeric addition. This is, by definition, an operator overload.

Here's the list of all Java operators:

JLS 3.12 Operators

The following 37 tokens are the operators, formed from ASCII characters:

  =     >     <     !     ~     ?      :
  ==    <=    >=    !=    &&    ||     ++     --
  +     -     *     /     &     |      ^      %     <<     >>    >>>
  +=    -=    *=    /=    &=    |=     ^=     %=    <<=    >>=   >>>=

Some of those operators are overloaded. Here are some examples:

System.out.println(   3 + 4 + "X"     ); // prints "7X"
System.out.println(   3 + (4 + "X")   ); // prints "34X"
System.out.println(   "X" + 3 + 4     ); // prints "X34"
System.out.println(   "X" + (3 + 4)   ); // prints "X7"

System.out.println(0 == 0);                           // prints "true"
System.out.println(new Integer(0) == new Integer(0)); // prints "false"

System.out.println(true & (1 & 2) == 12); // prints "false"

Can we overload the operators defined in the Java language?

ABSOLUTELY NOT! All Java operators mean exactly as specified by the language specification. There is no "extra-linguistic" semantics: a Java operator can NEVER do something that isn't specified by the language.

That is, unless the language changes, the following are guaranteed truths:

  • someString + whatever is ALWAYS string concatenation
  • referenceType == anotherReferenceType is ALWAYS reference equality
  • No funky things like 3 * "a lady" or "my heart" / 2 or even 10**3 ~= 999

As the above snippet shows, however, even the current state of operator overloading can still be quite confusing, especially for beginners. By not allowing extra-linguistic overloads, at least this confusion is limited: once a programmer learns about what all the operators in the Java language do in various overloaded scenarios, their exact semantics in all Java code becomes clear and precise.

Operator overloading can be quite confusing. Some think that it's "bad" enough as it is. To allow users to overload the Java operators to do something outside the language specification can only lead to even more confusion.

Here's an excerpt from Java Puzzlers, Puzzle 30: Son of Looper:

The lesson for language designers is the same as [two other puzzles]. Operator overloading can be confusing. Perhaps the + operator should not have been overloaded for string concatenation. It may well be worth providing a string concatenation operator, but it doesn't have to be +.


Do you need C++ to support operator overloading in Java?

NOPE! This has nothing to do with it at all. All that the Java compiler needs to do is parse the program source code according to the grammatical rules of the language, and determine, for each operator, what the types of the operands are. This information is enough to deduce what the meaning of the operator is, and to then act accordingly as specified by the language.


Appendix

JLS References

  • 15.18 Additive Operators
    • 15.18.1 String Concatenation Operator +
    • 15.18.2 Additive Operators (+ and -) for Numeric Types
  • 15.21 Equality Operators
    • 15.21.1 Numerical Equality Operators == and !=
    • 15.21.2 Boolean Equality Operators == and !=
    • 15.21.3 Reference Equality Operators == and !=
  • 15.22 Bitwise and Logical Operators
    • 15.22.1 Integer Bitwise Operators &, ^, and |
    • 15.22.2 Boolean Logical Operators &, ^, and |

Revealing questions

  • why does a char + another char = a weird number
  • Is it guaranteed that new Integer(i) == i in Java?
  • When comparing two Integers in Java does auto-unboxing occur?
  • Java String.equals versus ==
like image 45
polygenelubricants Avatar answered Oct 07 '22 17:10

polygenelubricants