public class TestClass{
public static void main(String args[ ] ){
Object a, b, c ;
a = new String("A");
b = new String("B");
a = b; //only swipe this code
c = a;
System.out.println(""+c);
}
}
I read your explanation , but can you please tell me why in above case it is printing B .
Also in explanation you have mentioned that "..c starts pointing to the string object .." where this happens compile time or run time.?
a = b; this assigns the objected pointed to by b (which is "B") to a. So a points to "B" now.
Then you have c = a; this assigns the objected pointed to by a (which is "B" because of above) to c. So c also points to "B" now.
System.out.println(""+c); // this prints B because c is pointing to B as explained above.
All this happens at run time.
If you like our products and services, please help us by posting your review here.
sugarkanke wrote:Why is Object's class toString method not used in this example?
You have asked a very fundamental question. And I would strongly suggest you to read about polymorphism in Java from a good book before attempting any further mock exams. You should come back to this question after reading that.
Why does the String's class toString() method overrides Object's?
I am not sure I understand your question. String's class toString() method overrides Object's toString because that is what the programmer (i.e. the one who coded String class) intended to do. Object's toString doesn't do what the String class wants to do.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.
So in this question c is pointing to a, and once a points to b, c is still sitting there pointing at new String("a") while a switched its reference and now points at new String("b")?