10.4. Passing Primitive Data Values

If primitive data types are passed as actual parameter, the value of the variable is copied to the formal parameter at method invocation. Since formal parameters are local to the method, any changes made to the formal parameter will not be reflected in the actual parameter after the call completes.

In other words, if a primitive variable (int, float, boolean etc) is passed as an argument, then a copy of the original variable is sent to the method. So if the called method changes the value of the argument, it does not get reflected in calling program. Remember the method is only operating on a copy of the variable.

			package javatutorial;

			 * Example class to learn about passing primitives to a method in Java
			 * @author f5java.com
			public class PassingPrimitives {
				public void displayPersonDetails(String name, int age){
					// primitive int age : receives a copy of the variable from calling method
					System.out.println("Received following input");
					System.out.println("Name: " + name + " Age: " + age);
					System.out.println("Changing the value of primitive int inside the method");
					// This change is local to the method and will not be reflected outside this method. 
					// i.e. this value is NOT reflected in the calling method  
					age = age - 5; 
					System.out.println("Values Now: ");
					System.out.println("Name: " + name + " Age: " + age);

				public static void main(String[] args) {
					// Fields
					String name = "Bob";
					int age= 50;
					System.out.println("Printing values in calling method before method call");
					System.out.println("Name: " + name + " Age: " + age);
					// Instantiate and call the method
					PassingPrimitives primitive = new PassingPrimitives();
					primitive.displayPersonDetails(name, age);
					System.out.println("Printing values in calling method after method call");
					System.out.println("Name: " + name + " Age: " + age);
					// Note the value of age doesn't get changed in the calling method