• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

code

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The code below should explain the concept.
 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 11604
178
Hibernate jQuery Eclipse IDE Spring MySQL Database AngularJS Tomcat Server Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanx everybody i got it
 
reply
    Bookmark Topic Watch Topic
  • New Topic