Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pass By Values / Pass By reference

 
Sarath Koiloth Ramath
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi frnds,


I read the k&B passing the variables and object.But land up with lots of doubts.Can any one please help me to understand the idea behing the pass by reference and pass by values.Is java using pass by values Or java using both.please give a good description

Thank
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java is strictly pass-by-value. What confuses people is that Java passes references by value too, which is not the same as pass-by-reference.

See this JavaRanch Campfire Story: Pass-by-Value Please
[ May 22, 2008: Message edited by: Jesper Young ]
 
Tusshar Fasate
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sarath,
Java use only pass by value.
and it doesnt use pass by reference.

here example

static void ranch(int a)
{
int b=b+a
}
in...main

{
int x=9;
ranch(x);

}

here value of x is copied to variable a
and whatever operaions made on a will not be reflected in x.


But its little confusing about array or any object refernce.

static void ranch(Test t)//Test is any class
{

}
in main...
{
Test t1=new Test();

ranch(t1);
....
...}
here also only one object is created and reference is sent to method ranch
so whatever operation made in ranch method will reflect to original object.its also call by value but bit of confusing.


Tushar...
Pune
India
 
Sarath Koiloth Ramath
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tusar,

I think i got it.i will try to explain.

While passing a primitive variable ,Java is passing the copy of the variable.when we pass an object, the reference(that may be an address reference,but pointing to the same object) is passing.hence we say pass by value.So any change made will be reflected in the original object.I am correct...
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12098
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sarath Koiloth Ramath:
So any change made will be reflected in the original object.
it depends on what you mean by 'any change'. if i do this:

 
Sarath Koiloth Ramath
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok Thanks..I got it...

Thanks once again tushar,Jesper ,and fred...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic