Reputation: 3
Lets take this example:
class Class
{
String object;
Class ob;
void display()
{
object= object+1;
ob = ob+1;
System.out.println(object +" "+ ob );
}
public static void main (String args[])
{
Class obj = new Class();
obj.display();
}
}
This gives a compile time error : bad operand types for binary operator + first type find ; second type : int. This error points at this line of my code ob = ob+1; .
However, when I eliminate this line, the program executes in a proper manner (printing the String as null1).
Now my question is, that object and ob are both objects of class String and class Class respectively so why/how am I able to add 1 to null value of object and not that of ob?
Upvotes: 0
Views: 371
Reputation: 103
The full answer is that for class variables Java initializes them with special values for primitives + String, and with null for every other object. As for local variables (e.g. defined inside a method ) Java doesn't do anything with them. The error you are getting is caused by the lack of + operator for any other types than primitives or Strings.
If you move the definition String object;
inside the method your code won't work at all, both object
and ob
will be unasigned.
Upvotes: 0
Reputation: 48258
Lets suppose you have this class
class Foo {
provate int x;
private int y;
}
if you do Foo myFoo +=1, what do you accept as a logically correct result operation? myFoo.x+=1;
?? , myFoo.y+=1;
?? or maybe myFoo.x+=1 and myFoo.y+=1;
??
Java doesnt support overloading of unary operators so something like
class Foo {}
Foo +=1;
is not valid and not compiling (until now) no matter if Foo has field that do support that operation, String class is one exception that allows you to do that
Upvotes: 0
Reputation: 10995
Java does not support operator overloading. You can only use operators such as +
, -
, *
, /
, <<
, >>
, |
, ^
, >>>
, <<
, etc. on primitive types and on String
objects. You cannot implement those operators on instances of your own class.
See this question to understand why java does not allow overriding this behavior.
Upvotes: 0
Reputation: 61969
The reason why this works is because the java compiler has specific knowledge of the String
class and knows how to do special things with it, one of which is addition.
When you add something to a string object, the java compiler will replace your addition with code that converts the operand to string (by invoking toString()
) and then issue a call to String.concat()
. And if you add many strings together in one statement, it will create a StringBuilder
and invoke append()
to it multiple times, then take the toString()
of the StringBuilder
.
Upvotes: 1