0

I've just started learning Java. I'm reading this book: Intro to Java Programming, Comprehensive Version (10th_Edition). In chapter 9, there's a simple program:

import java.util.Date;
public class Test {

public static void main(String[] args) {

Date date = null;

m1(date);

System.out.println(date);

}

public static void m1(Date date) {

date = new Date();

}

}

As I understand the method creates a new object and assigns It to the reference variable that was passed to It. Why does It still print null after calling the method? Thanks for your answers.

James
  • 19
  • 1
  • 4

1 Answers1

0

In this method

public static void m1(Date date) {

    date = new Date();

}

You're not actually changing the real value of date. date is simply a local variable copied into the method. When m1 exits, date loses scope and is destroyed. You haven't made any real change to it (as in, the argument passed in).

Michael
  • 2,673
  • 1
  • 16
  • 27