Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between two programs

 
Chandra Moulee
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to know why when integer is passed to the function it does change the value whereas when passing a vector to the function changes the value in the class Funct1.Program one prints Vector's first element as "a".
While program two prints integer values i as 0.

1) Passing a vector to a function


Passing a int to the Function

Thanks
Mouli
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15203
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arguments to methods are passed by value in Java.

That means that if you pass an int, the int inside the method is a new variable, with the value of the int that you passed in - it's not the same, original int. So if you change the value, you're not changing the value of the original int.

If you pass a vector, you're passing the reference to the Vector object to the method. So you pass a reference by value. The variable in the method points to the same Vector object as the original variable, so you can change the Vector object that the reference points to.
 
Ishan Bhatt
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java is pass-by-value.

For primitives like int, you pass a copy of the actual value.

For references to objects like v1 (Vector v1 = new Vector()), you pass a copy of the reference (the remote control).

The campfire story "Pass-by-Value Please" should be more helpful in explaining this.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps you can see the difference if you try something like this:

This is analogous to your version with int because it is creates a new Vector to assign to the reference. In the same way, you are assigning a new int to the variable. In either case, this does not change the variable in the caller.

However, as explained above, when you call methods on an object, it will affect the state of the object no matter which reference (in the method or in main) that you use.

HTH

Layne
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic