I've been looking at samples from Core Java volume I and worked out some minor code.
import java.util.Date;
import java.util.GregorianCalendar;
class Test {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("Tony Tester", 40000, 1990, 3, 15);
System.out.println("initial hireDay: " + staff[0].getHireDay());
Date d = staff[0].getHireDay();
double tenYearsInMilliSeconds = 10 * 365.25 * 24 * 60 * 60 * 1000;
d.setTime(d.getTime() - (long) tenYearsInMilliSeconds);
System.out.println("d: " + d);
System.out.println("modified hireDay: " + staff[0].getHireDay());
System.out.println("initial salary: " + staff[0].getSalary());
int j = staff[0].getSalary();
j += 10;
System.out.println("j: " + j);
System.out.println("modified salary: " + staff[0].getSalary());
}
}
class Employee {
private int salary;
private Date hireDay;
public Employee(String n, int s, int year, int month, int day) {
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public int getSalary() {
return salary;
}
public Date getHireDay() {
return (Date) hireDay;
}
}
Output:
initial hireDay: Thu Mar 15 00:00:00 EST 1990
d: Fri Mar 14 12:00:00 EST 1980
modified hireDay: Fri Mar 14 12:00:00 EST 1980
initial salary: 40000
j: 40010
modified salary: 40000
In the example, the final value of 'salary' hasn't changed while the final value of 'hireDay' has changed. How does this happen?? Is it that the 'salary' has been passed by value where as 'hireDay' has been passed by reference?? But then, I came across this post where it's been mentioned that all the passing in java is by value. If so, how can the value of 'hireDay' change?? Does this have something to do with the 'Date' class being mutable??
Thanks in advance...