package examples;
public class PrimativeDataToMethod {
public static void main(String[] args) {
// primitive data to method
int num1 = 10;
int num2 = 20;
PriCheck pri = new PriCheck();
pri.swap(num1, num2);
System.out.println("Outside method dont swap" + num1 + '\t' + num2);
System.out.println("");
// Object to method
Employee E1 = new Employee(100);
Employee E2 = new Employee(200);
System.out.println("BEFORE "+"E1 " + E1.empId + '\t' + "E2 " + E2.empId);
// call the swap method
SwpEmpID swap = new SwpEmpID();
swap.swap(E1, E2);
System.out
.println("AFTER " + "E1 " + E1.empId + '\t' + "E2 " + E2.empId);
}
}
// passing primitive data to method
class PriCheck {
// swap num1 and num2 within method
public void swap(int num1, int num2) {
int tmp;
tmp = num1;
num1 = num2;
num2 = tmp;
System.out.println("within method swap " + num1 + '\t' + num2);
}
}
// create a employee class
class Employee {
int empId;
public Employee(int empId) {
this.empId = empId;
}
}
// passing object to method
class SwpEmpID {
public void swap(Employee E1, Employee E2) // passing Employee object to
// method to swap object
{
Employee tmp;
tmp = E1;
E1 = E2;
E2 = tmp;
// access instance variable of Object E1 and E2 within method
System.out.println("instance variable of Object E1 and E2 WITHIN method "
+ E1.empId+'\t'+E2.empId);
}
}
Thursday, September 10, 2015
Java pass by value
Labels:
Java Basics
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment