So am i wrong to think ,by callby reference we can permanently change object's value. No, you are not wrong about how 'pass by reference' works.
it still prints 2.but according to me now it should be 4. Subha already tried to explain this to you: The variable a in class callby is an
instance variable. Each object that you create out of class callby will have its own variable named a, which will be initialized to the value 2. This is what happens in your original example:
1. In the line before "line a", you create a new callby object. The value of its variable a is initialized to 2.
2. In "line a", you multiply the value of a in that object by 2, so the value is now 4.
3. In "line b", you print the contents of the variable a in the object, so you get 4.
4. In "line c", you create a new, different callby object. It has its own variable a which is initialized to 2, and that's what you print.
Your example doesn't do anything with 'pass by reference'.
Have a look at these topics in Sun's
Java Tutorials:
Object-Oriented Programming Concepts Classes and Objects Understanding Instance and Class Members By the way, 'pass by reference' does not exist in Java; Java is strictly 'pass by value'. To understand this, read the JavaRanch Campfire story
Pass-by-Value Please.