Variable declarations and Pass by value

Variables are declared using this structure.

[access keywords] [special keywords] Type varname;, and they are initialized using this structure varname = initial value;. It is common to see the declaration and initialization on the same line, thus giving us this structure

[access keywords][special keywords] Type varname = initial value;

The access keywords and special keywords are optional, if you don’t declare, then the variable is automatically package access and it belongs to instance (object), a regular instance variable.

There are 2 kinds of variables that you can declare, a primitive type variable and a reference type variable. A primitive variable is any of the 8 primitive data types defined in Java; and reference types, well, anything that is not primitive is of reference type — that’s probably not a helpful definition, let’s try again; A reference type returns an address of an object, you can tell because you will use the “new” keyword in Java, and you know that when you use the new keyword

Passing parameters to functions

Java manipulates objects by references, however, but it does not pass parameters to functions by reference, everything is passed by value. This could be counter intuitive if you’re coming from another language like C or C++, hence, you cannot write your traditional swap function in Java.

When you pass variables as function parameters, the function creates a copy of the passed parameters inside the function, as local variables. Which means whatever you do with the variable, change it’s value etc, it will not impact the copy of the variable outside the function.

Look at this code.

//
//
class Foo {

	void go() {

		int sample1 = 10;
		String sample2 = "Hello";

		goo(sample1, sample2);
		System.out.println("Sample 1 = " + sample1);
		System.out.println("Sample 2 = " + sample2);

	}

	void goo(int args1, String args2) {
		args1 = 100;
		args2 = new String("World");
	}

	public static void main(String []args) {
		new Foo().go();
	}

}

You’d expect that since sample2 is a reference type, that function go() passed the address of sample2 to goo() when it was invoked, but no, it did not pass the reference, it created a copy for goo(), that is why the value of sample 2 is left unchanged when we printed it using System.out.

If you want to show appreciation for my efforts dear reader, you could buy me a tall hazel nut Americano ($2) via PayPal. Thanks
Post navigation
(previous post)
(next post)
| | | | .

{0 Comments .. you can add one }

Leave a comment