• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

code

 
hemamalini s.
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q14 public class Test14{
static String s ="Instance";
public static void method(String s){
s+="Add";
}
public static void main(String a[]){
Test14 t = new Test14();
s = "New Instance";
String s = "Local";
method(s);
System.out.println(s);
System.out.println(t.s);
}
}
What is output?
output is locan new instance.
How?
Thanx
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code below should explain the concept.
 
Mandy Hou
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
there is a copy of refence passed into call method.
So both this.s and local s are not changed
 
Roel De Nijs
Sheriff
Posts: 9934
113
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i believe the complete explanation goes as follows:
when you pass an object to a method you are passing a copy of the value of an original variable. this value contains a bit pattern of a way to refer to an object. So: you can change the object's members by both: the argument in the method and the original variable, but not let the original value point to another object (you can let the argument refer to another object).

because strings are immutable, you can't change them and always a new string is created, so the argument refers to the new string, but the original variable still refers to the original string
 
hemamalini s.
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx everybody i got it
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic