• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Passing ref

 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class pass{



public static void main(String a[]){


String i="Hi";
m1(i);
System.out.println(i);

}
static void m1(String a){
a +="Welome ";
}

}


Why this does not print Hi Welcome ?
 
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Coz variable i & a both point to the same String object in memory which will have value of "HiWelcome" after m1(i) and while printing i.

Regards.
 
Ram Han
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Do you say a and i will have "HiWelcome" ?
 
Mehul Sanghvi
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I am sorry about the previous reply... it is wrong!

Well the reason it just print 'Hi' and not 'HiWelcome' is because, String is a non-mutable object hence when a+="Welcome" is executed, a new String object is created in memory with the value 'HiWelcome' and the address will be assigned to a, while the i will still point to the old String object with the value of 'Hi', and hence the output is 'Hi'.

Regards.
 
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Strings are immutable. Thats why output is 'Hi';
Try the same logic with StringBuffer (StringBuffers are mutable)


class Pass{
public static void main(String a[])
{
StringBuffer i=new StringBuffer("Hi");
m1(i);
System.out.println(i);
}
static void m1(StringBuffer a)
{
a.append("Welome ");
}

}//pass


output:
HiWelcome
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic