Topics

6/recent/ticker-posts

Message Passing in Java

Message Passing in java  

  • - Pass-by-value
  • - Pass-by-reference

Pass-by-value

  • Primitive members (int, long, float, double, char, boolean) passed as arguments into method are called as pass-by-value. 
  • In pass-by-value the value of the variable is copied into method argument, so that even though the parameter value changes in the methods the /argument or value doesn't reflect in the original copy.

// PBV.java

class PBV {

public static void main(String rags[]) {

int age=18;

double sal=50000.00;

char ch='A';

boolean yesorno=true;

System.out.println("Before pbv "+age+" "+salary+" "+ch+" "+yesorno);

// pass-by-value

modify(age, sal, ch, yesorno);

System.out.println("After pbv "+age+" "+salary+" "+ch+" "+yesorno);

}

public static void modify(int i, double d, char c, boolean b) {

i+=10;

d+=10000.00;

c='B';

b=false;

System.out.println("In modify "+i+" "+d+" "+c+" "+b);

}

}


Pass-by-reference

  • Arrays and all objects except String passed as arguments into method are called as pass-by-reference. 
  • In pass-by-reference the address of the object is passed into method, so that if any changes made to object in the method will be modified in the origin object also.


class Emp {

   int eid;

   String ename;

   double sal;

   String desig;

   

   Emp() {}

   Emp(int id, String en, double sa, String de) {

      eid=id;

  ename=en;

  sal=sa;

  desig=de;

   }


   public String toString() {

      return eid+" "+ename+" "+sal+" "+desig;

   }

}

 

// PassByReference.java

public class PassByReference {

    public static void main(String rags[]) {

double d[]={10.24, 20.45, 30.65};

    Emp e=new Emp(1, "ABC", 100000.00, "Architect");

passByReference(d, e);

for(double d1:d) {

       System.out.println(d1); // 40.89, 20.45, 30.65

}

System.out.println(e); // 1 Mr. ABC 200000.00 Architect

}

public static void passByReference(double d[], Emp e) {

   d[0]=40.89;

   e.ename="Mr. "+e.ename;

   e.sal=e.sal+e.sal;

}

}

 

Access specifiers that can be applied on:

class: default, public

var: all 4

constr: all 4

method: all 4


Access modifiers that can be applied on:

class: abstract, final

var: static, final, volatile, transient

constr: No access modifier

method: abstract, final, static, native, synchronized


We hope this post helped more about learning Message passing in java. 
You may also want to see 





Post a Comment

2 Comments