File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Difference between two programs Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difference between two programs" Watch "Difference between two programs" New topic

Difference between two programs

Chandra Moulee

Joined: Sep 26, 2005
Posts: 16
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

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Ishan Bhatt

Joined: Oct 09, 2005
Posts: 14
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

Joined: Dec 06, 2001
Posts: 3061
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.



Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: Difference between two programs
It's not a secret anymore!