The Artima Developer Community
Sponsored Link

Java Answers Forum
Parameters in Java

1 reply on 1 page. Most recent reply: Mar 17, 2002 9:55 AM by Kishori Sharan

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Bob

Posts: 4
Nickname: turshu
Registered: Mar, 2002

Parameters in Java Posted: Mar 17, 2002 9:12 AM
Reply to this message Reply
Advertisement
Parameters in Java are always passed by value yet a method call cause the attributes of an oject parameter to be updated.Why is this?


Kishori Sharan

Posts: 211
Nickname: kishori
Registered: Feb, 2002

Re: Parameters in Java Posted: Mar 17, 2002 9:55 AM
Reply to this message Reply
> Parameters in Java are always passed by value yet a
> method call cause the attributes of an oject
> parameter to be updated.Why is this?

Let us take an example.
yourobjectreference yor = new yourobject() ;

aMethod ( yor ) ;

By saying, all parameters are passed by value in Java, we are saying that the reference to your object, which is yor, is passed by value to the method aMethod. Here, we are not passing the object itself, rather a reference to the object. Since, yor is passed by value to aMethod, even if we set yor to some other object within aMethod our original reference yor doesn't change. It still refers to the original object. However, the copy of yor is passed to aMethod and this copy also is a reference to the same object which yor is refering to. Since, yor and the copy of yor inside aMethod, both are reference to the same object they are capable of affecting the object in same way. So, inside aMethod you can change the object. For example,

yourobjectreference yor = object1 ;
 
aMethod ( yourobjectreference yorCopy ) {
  // Here yorCopy also refers to object1.
  // However, yorCopy is a copy of yor and
  // it is because parameters are passed by value
  // in Java. Since yorCopy also refers to object1
  // you can change object1, if you really can, using
  // methods and properties of objects1.
  // Important thing is if you say,
   yorCopy = object2 ;
  // Then only yorCopy is now refering to object2
  // and yor is still refering to object1. This is
  // what we mean by saying that all parameters
  // are passed by value in java
}

Thanks
Kishori

Flat View: This topic has 1 reply on 1 page
Topic: New to Java confusion with output/CheckBox and GUI? Previous Topic   Next Topic Topic: Help with an Array of strings

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use