Java Lesson 7-3
Java Lesson 7-3
Parameter Passing
Dr. Ei Ei Moe
Lecturer
©https://blogs.ashrithgn.com/
Objectives
• To understand how the arguments are passed to the parameters using the pass-by-
value scheme
• To know how to declare reserved word static in class method and variable
• When you pass an item of a simple data type to a method, Java passes a copy of the
data in the item, which is called passing by value.
• Because the method gets only a copy of the data item, the code in the method cannot
affect the original data item at all.
• When you pass an object to a method, Java actually passes a reference to the object,
which is called passing by reference.
• Passing by reference means that the code in the method can reach the original
object.
• In fact, any changes made to the passed object affect the original object.
class Employee {
int salary; public class EmployeeMain {
String name; public static void main(String[] args) {
Employee(int sal, String empname) { Employee empobj = new Employee(500, “Aye Aye”);
salary = sal; System.out.println(empobj.salary+ “ ”+
name = empname; }
empobj.name);
empobj.passByValue(empobj.salary);
public void passByValue(int sal) {
System.out.println(“Salary : ”+ sal); System.out.println(empobj.salary);
int increaseSalary = sal + 100; Output
}}
System.out.println(“Increase Salary :”+increaseSalary); 500 Aye Aye
} Salary : 500
Increase Salary :600
} 500
Faculty of Computer Science
Example: Pass-by-Reference
class Employee {
public class EmployeeMain {
int salary;
String name; public static void main(String[] args) {
Employee(int sal, String empname) {
Employee empobj = new Employee(500, “Aye Aye”);
salary = sal;
name = empname; System.out.println(empobj.salary + “” +
}
empobj.name);
public void passByReference(Employee emp) {
empobj.passByReference(empobj);
System.out.println(“Original Name ” + emp.name);
Employee e = emp; System.out.println(empobj.name);
}}
Output
e.name = “Su Su”;
500 Aye Aye
System.out.println(“Update Name:” + e.name); Original Name Aye Aye
}} Update Name:Su Su
Su Su
Faculty of Computer Science
Define Class Methods and Variables
• Static keyword can be used with class, variable, method, and block.
public static void main(String[] args) { public static int min(int num1, int num2) {
int i = 2;
int j = 5; int result;
public static void main(String[] args) { public static int min(int num1, int num2) {
int i = 2; (num1 < num2) is true
int j = 5; int result; since num1 is 2 and num2
is 5
int k = min(i, j); if (num1 < num2)
result = num1; result is now 2
System.out.println( "The minimum between " + else
i + " and " + j + " is " + k); result = num2;
} return result;
}
• The correct way to reuse programmer-defined classes from many different programs
is to place reusable classes in a package.
import myutil.*;
class MyClass {
Student s1;
...
}
NEXT Topic
• Exception Handling