/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2015 * Time: 8:12 PM */ Core Java test2

Methods, call by value and call by reference

Core Java

Methods in Java and it's Importance

A Java method is a collection of statements that are grouped together to perform an operation.
At times, a certain portion of codes has to be used many times. Instead of re-writing the codes again and again, it is better to put them into a "singlePlace", and "call" them many time - for ease of maintenance and understanding. the place where you put those code is called method (in Java) or function (in C/C++).
The benefits of using methods are


Creating a Method (function) :-
A method definition consists of a method header and a method body.
Here are all the parts of a method:

Here is an Example :-

/** Return the max between two numbers */
public static int max(int num1, int num2) {
   int result;
   if (num1 > num2)
      result = num1;
      result = num2;

   return result;

Passing Parameters by Values:

When calling a method, you need to provide arguments, which must be given in the same order as their respective parameters in the method specification. This is known as parameter order association.
For example, the following method prints a message n times:

	public static void nPrintln(String message, int n) {
	  for (int i = 0; i < n; i++)

Here, you can use nPrintln("Hello", 3) to print "Hello" three times. The nPrintln("Hello", 3) statement passes the actual string parameter, "Hello", to the parameter, message; passes 3 to n; and prints "Hello" three times. However, the statement nPrintln(3, "Hello") would be wrong.

Example of PassByValue - Swap two values in java

Following is a program that demonstrates the effect of passing by value. The program creates a method for swapping two variables. The swap method is invoked by passing two arguments. Interestingly, the values of the arguments are not changed after the method is invoked.

public class PassByValueExample {

   public static void main(String[] args) {
      int num1 = 1;
      int num2 = 2;

      System.out.println("Before swap method, num1 is " +
                          num1 + " and num2 is " + num2);

      // Invoke the swap method
      swap(num1, num2);
      System.out.println("After swap method, num1 is " +
                         num1 + " and num2 is " + num2);
   /** Method to swap two variables */
   public static void swap(int n1, int n2) {
      System.out.println("\tInside the swap method");
      System.out.println("\t\tBefore swapping n1 is " + n1 + " n2 is " + n2);
      // Swap n1 with n2
      int temp = n1;
      n1 = n2;
      n2 = temp;

      System.out.println("\t\tAfter swapping n1 is " + n1+ " n2 is " + n2);

	Output :-
	Before swap method, num1 is 1 and num2 is 2
	Inside the swap method
    Before swapping n1 is 1 n2 is 2
    After swapping n1 is 2 n2 is 1
	After swap method, num1 is 1 and num2 is 2

Pass by Reference

The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.
The difficult thing can be to understand that Java passes "objects as references" passed by value.
This can certainly get confusing and I would recommend reading this article

Object variables in parameters are more complicated than primitive variables. Since object variables are essentially references to objects, the values passed to object variables in parameters are references (not objects themselves). In the next example,

testJavaProperty() accepts two parameters:
one is an array, and the other is an integer. Since arrays are objects, the parameter variable x refers to the same array as the variable arr from the calling code.

Thus, the increase of the first element of the array is still effective after the method returns.

Example of PassByReference

package javaessential.com.interview;

public class JavaPassByvalueVsReference {

    public static void testJavaProperty(int[] a, int y){

    public static void main(String str[]){
	int a[] = {9,4,7};
	int y = 9;
	System.out.println("Values before call the method is ");
	for(int i :a){
	    System.out.println("value of a is "+ i);
	System.out.println("value of y is "+y);
	testJavaProperty(a, y);

	System.out.println("Values after call the method is ");
	for(int i :a){
	    System.out.println("value of a is "+ i);
	System.out.println("value of y is "+y);

	Output :-
		Values before call the method is
		value of a is 9
		value of a is 4
		value of a is 7
		value of y is 9
		Values after call the method is
		value of a is 10
		value of a is 4
		value of a is 7
		value of y is 9

Varargs - Method with Variable Number of Formal Arguments (JDK 1.5) :-

Before JDK 1.5, a method has to be declared with a fixed number of formal arguments. C-like printf(), which take a variable number of argument, cannot not be implemented. Although you can use an array for passing a variable number of arguments, it is not neat and requires some programming efforts. JDK 1.5 introduces variable arguments (or varargs) and a new syntax "Type...".
For example,

public PrintWriter printf(String format, Object... args)
public PrintWriter printf(Local l, String format, Object... args)

Varargs can be used only for the last argument. The three dots (...) indicate that the last argument may be passed as an array or as a sequence of comma-separated arguments. The compiler automatically packs the varargs into an array. You could then retrieve and process each of these arguments inside the method's body as an array. It is possible to pass varargs as an array, becuase Java maintains the length of the array in an associated variable length.


For method overloading and Overriding please referer OOP concept

Continue/ Next Page
Previous Page

Click here to access OOp's Concept

feel free to ask any of your doubts