Passing Parameters or Arguments in JAVA


Passing Parameters or arguments

 

In Java we can pass the parameters to a method or to a constructor.

 

We use the termformal parameters to refer to the parameters in the definition of the method.

public int mult(int x, int y)

We use the term actual parameters to refer to variables in the method call, in this case length and width. They are called “actual” because they determine the actual values that are sent to the method.

To refer the variables in method call

mult(length, width);

Java Supports only Pass-by-value

 

Pass-by-value

 

Pass-by-value means that when you call a method, a copy of the value of each actual parameter is passed to the method.   You can change that copy inside the method, but this will have no effect on the actual parameter.

 

if a Java variable is a cup, with a value in it, what does it mean to “pass” a variable to a method? And are primitives and references treated the same way?

We’ll get there, but first let’s start with simple assignment.

What does it mean to say:

1) int x = 3;

2) int y = x;

In line 1, a cup called x, of size int, is created and given the value 3.

In line 2, a cup called y, of size int, is created and given the value… 3.

The x variable is not affected!

Java COPIES the value of x (which is 3) and puts that COPY into y.

This is PASS-BY-VALUE. Which you can think of as PASS-BY-COPY. The value is copied, and that’s what gets shoved into the new cup. You don’t stuff one cup into another one.

 

 

 

 

 

Pass-by-Reference

 

Pass-by-Reference means the method will operate on the original value itself. It does not work on a copy of a argument

 

Pass by value with object Reference

With objects the objects Reference itself is passed by value and so both the original reference and parameter copy both and they refer to the same object.

 

 

 

 

Passing Primitive Types WITHOUT RETURN TYPE

class PassPrim

{

public static void main(int i, double f, char c, boolean test)

{

System.out.println(“This works dummy main”);

 

i += 10; //This is legal, but the new values

c = ‘z’; //won’t be seen outside tryPrimitives.

if(test)

test = false;

else

test = true;

f = 1.5;

System.out.println(“ii = ” + i + “, ff = ” + f +”, cc = ” + c + “test” +test);

// return i;

}

public static void anyway()

{

System.out.println(“This works Anyway”);

int i=1;

i++;

double f=1.0;

char c=’a’;

boolean b=false;

main(i, f, c, b); //calls main function and passes the arguments

System.out.println(“ii = ” + i + “, ff = ” + f +”, cc = ” + c + “, bb = ” + b);

}

public static void main(String[] args)

{

System.out.println(“This works”);

}

static //Executes first

{

System.out.println(“This works Static block “);

anyway(); //calls anyway Function

}

}

/* What’s really happening here? When Java calls a method, it makes a copy of its actual parameters’ values and

sends the copies to the method where they become the values of the formal parameters. Then when the method returns,

those copies are discarded and the actual parameters have remained unchanged.*/

 

 

//Passing Parameter with return type

 

 

class PassRetPrim

{

public static int power(int a, int b)

{

System.out.println(“New value of number is ” +a);

System.out.println(“New value of number is ” +b);

int i;

int total = 1;

for(i = 0; i < b; i++) //logic for math of base and power

total = total * a;

return total;

}

public static void main(String args[])

{

int number = 2;

int exponent = 4;

int z = power(number, exponent); //calls and assigns the value of power method

System.out.println(“New value of number is ” +z);

System.out.println(“New value of number is ” +number);

System.out.println(“New value of number is ” +exponent);

}

}

 

//Pass by value with object Reference

 

Java passes everything by value. With primitives, you get a copy of the contents. With references you get a copy of the contents.

But what is the contents of a reference?

The remote control. The means to control / access the object.

When you pass an object reference into a method, you are passing a COPY of the REFERENCE. A clone of the remote control. The object is still sitting out there, waiting for someone to use a remote.The object doesn’t care how many remotes are “programmed” to control it. Only the garbage collector cares (and you, the programmer).

So when you say:

Cat A = new Cat();
doStuff(A);

void doStuff(Cat B) {

   // use B in some way
}

There is still just ONE Cat object. But now TWO remote controls (references) can access that same Cat object.

So now, anything that B does to the Cat, will affect the Cat that A refers to, but it won’t affect the A cup!

You can change the Cat, using your new B reference (copied directly from A), but you can’t change A.

 

You can change the object A refers to, but you can’t take the A reference variable and do something to it — like redirect it to reference a different object, or null.

So if you change the B reference (not the Cat object B refers to, but the B reference itself) you don’t change A. And the opposite is true.

So…

Cat A = new Cat();
doStuff(A);

void doStuff(Cat B) {

   B = new Cat(); //did NOT affect the A reference
}

Doing this simply “points” B to control a different object. A is still happy.

So repeat after me:

Java is pass-by-value.

(OK, once again… with feeling.)

Java is pass-by-value.

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

For references to objects, you pass a copy of the reference (the remote control).

 

 

 

class PassObjRef

{

int num;

String name;

public static void tryObject(PassObjRef r)

{

r.num = 100;

r.name = “Fred”;

}

public static void main(String args[])

{

PassObjRef id = new PassObjRef();

id.num = 2;

id.name = “Barney”;

tryObject(id);

System.out.println(id.name + ” ” + id.num);

}

}

 

 

 

 

 

 

Passing Arrays
Arrays are references. This means that when we pass an array as a parameter, we are passing its handle or reference. So, we can change the contents of the array inside the method.*/

 

Array with Primitives

 

class PassArr

{

 

public static void tryArray(char[] b)

{

b[0] = ‘x’;

b[1] = ‘y’;

b[2] = ‘z’;

}

 

//When the following code is executed, the array a does indeed have the new values in the array.

public static void main(String[] args)

{

char[] a = {‘a’, ‘b’, ‘c’};

System.out.println(“a[0] = ” + a[0] + “, a[1] = ” + a[1] +”, a[2] =” + a[2]);

tryArray(a);

System.out.println(“a[0] = ” + a[0] + “, a[1] = ” + a[1] +”, a[2] =” + a[2]);

}

}

 

 

 

 

 

Array with Reference variables

 

class PassArr1

{

 

public static void tryArray(PassArr1 a[])

{

s

a[0]=new PassArr1();

a[1]=new PassArr1();

a[2]=new PassArr1();

System.out.println(“a[0] = ” + a[0] + “, a[1] = ” + a[1] +”, a[2] =” + a[2]);

}

 

//When the following code is executed, the array a does indeed have the new values in the array.

public static void main(String[] args)

{

 

PassArr1[] k=new PassArr1[4];

k[0]=new PassArr1();

k[1]=new PassArr1();

k[2]=new PassArr1();

tryArray(k);

System.out.println(“k[0] = ” + k[0] + “, k[1] = ” + k[1] +”, k[2] =” + k[2]);

}

}

 

 

/* output is

a[0] = PassArr1@18b429b, a[1] = PassArr1@1c20c74, a[2] =PassArr1@bfa709

k[0] = PassArr1@18b429b, k[1] = PassArr1@1c20c74, k[2] =PassArr1@bfa709

*/

 

 

Passing String

 

String is an object, not a primitive. A new is indeed required; it’s just that Java does it behind the scenes. Java creates a new object of class String and initializes it to contain the string literal we have given it.
Because str is an object, we might think that the string it contains can be changed when we pass str as a parameter to a method. Suppose we have the method tryString

 

class PassStr

{

// String str = “This is a string literal.”;

public static void tryString(String s)

{

s = “a different string”;

}

public static void main(String args[])

{

String str = “This is a string literal.”;

tryString(str);

System.out.println(“str = ” + str);

}

}

 

 

When it assigns a string literal to an object. A different String object is created and the reference variable is set to point to the newly created object. In other words the value of the formal parameter, s, has changed, but this does not affect the actual parameter str. In this example, s pointed to the string object that contains “This is a string literal”. After the first statement of the method executes, s points to the new string, but str has not changed.

//////Doubt

Like other objects, when we pass a string to a method, we can in principle, change things inside the object (although we can’t change which string is referenced, as we just saw). However, this capability is not useful with string because strings are “immutable”. They cannot be changed because the String class does not provide any methods for modification.

 

 

String Reference Variable in a Program

 

public class TestPassByReference {

public static void main(String[] args) {

// declare and initialize variables and objects

int i = 25;

String s = “Java is fun!”;

StringBuffer sb = new StringBuffer(“Hello, world”);

 

// print variable i and objects s and sb

System.out.println(i); // print it (1)

System.out.println(s); // print it (2)

System.out.println(sb); // print it (3)

 

// attempt to change i, s, and sb using methods

iMethod(i);

sMethod(s);

sbMethod(sb);

 

// print variable i and objects s and sb (again)

System.out.println(i); // print it (7)

System.out.println(s); // print it (8)

System.out.println(sb); // print it (9)

 

}

 

public static void iMethod(int iTest) {

iTest = 9; // change it

System.out.println(iTest); // print it (4)

return;

}

 

public static void sMethod(String sTest) {

sTest = sTest.substring(8, 11); // change it

System.out.println(sTest); // print it (5)

return;

}

 

public static void sbMethod(StringBuffer sbTest) {

sbTest = sbTest.insert(7, “Java “); // change it

System.out.println(sbTest); // print it (6)

return;

}

}

 

The value of the original variable cannot be changed within the method. This seems reasonable because the method only has a copy of the value; it does not have access to the original variable. This process is called pass by value.

 

We often say things like, “this method returns an object …”, or “this method is passed an object as an argument …” But this is not quite true, more precisely, we should say, something like “this method returns a reference to an object …” or “this method is passed a reference to an object as an argument …

Generally, objects are never passed to methods or returned by methods. It is always “a reference to an object” that is passed or returned. In general, pass by value refers to passing a constant or a variable holding a primitive data type to a method, and pass by reference refers to passing an object variable to a method. In both cases a copy of the variable is passed to the method. It is a copy of the “value” for a primitive data type variable; it is a copy of the “reference” for an object variable. So, a method receiving an object variable as an argument receives a copy of the reference to the original object.

Here’s the clincher: If the method uses that reference to make changes to the object, then the original object is changed. This is reasonable because both the original reference and the copy of the reference “refer to” to same thing — the original object. There is one exception: strings. Since String objects are immutable in Java, a method that is passed a reference to a String object cannot change the original object.

 

 

 

Unlimited Arguments

 

public class UnlimitedArgs {

 

/** Default constructor */

public UnlimitedArgs() {

}

 

public static void main(String args[])

{

UnlimitedArgs g = new UnlimitedArgs();

g.viewObjArgs(“Mega_unknown@hotmail.com”,1.100,1111,1.2,411,552555.66);

g.viewIntArgs(5,10,21,23,43,43,53,45,43,23,44);

}

 

/**

* Unlimited Argument List like printf in C++,Java .Holds int Type.

* unlimited int values

*/

private void viewIntArgs(int … Numbers){

for(int i : Numbers)

{

System.out.println(i);

}

System.out.println(“Lenght of my argument list is : ” + Numbers.length);

}

 

//What if we dont know object type. So we will set data type as Object

/**

*Unlimited Argument List like printf in C++,Java .Holds Object Type.

*/

private void viewObjArgs(Object … objects)

{

for(Object obj:objects)

{

//return type name

System.out.println(obj.getClass());

}

System.out.println(“Lenght of my argument list is : ” + objects.length);

}

}

 

 

 

 

About pacesettergraam

A good and realistic person

Posted on December 23, 2012, in Java and tagged , , . Bookmark the permalink. 3 Comments.

  1. Hey Superb n very nice Frd
    den awesome Explanation!!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: