CODE
class PassByReference
{
public static void main(String args[])
{
Student sMain = new Student();
sMain.name = "Jagan";
sMain.marks = 93;
sMain.section = 'B';
System.out.println("Marks before incrementing : " + sMain.marks);
incrementMarks(sMain);
System.out.println("Marks after incrementing : " + sMain.marks);
}
public static void incrementMarks(Student sMethod)
{
System.out.println("Marks before incrementing in the method: " + sMethod.marks);
sMethod.marks = sMethod.marks + 1;
System.out.println("Marks after incrementing in the method: " + sMethod.marks);
}
}
class Student
{
String name;
int marks;
char section;
}
Marks before incrementing : 93
Marks before incrementing in the method: 93
Marks after incrementing in the method: 94
Marks after incrementing : 94
Here we created a method called incrementMarks
which takes a Student
object as a parameter. Since the Student
is not a primitive data type, the object is passed by reference. When the marks are incremented in the incrementMarks
method, the marks
are also reflected in the main method. That is why when the marks are printed after incrementing, the value 94 is printed.
incrementMarks
method, change the section to 'Z'
. In the main
method print the section before and after calling the incrementMarks
method and observe that the value changes from 'B'
to 'Z'
.