Issue
Java 8
public class OidDTO {
private String value;
public OidDTO(String value) {
this.value = value;
}
}
Here Junit test:
@Test
public void change_object_by_ref() {
OidDTO oidDTO = new OidDTO("init_value");
changeOidDTO(oidDTO);
String expected = "new_value";
String actual = oidDTO.getValue();
assertEquals(expected, actual);
}
private void changeOidDTO(OidDTO oidDTO) {
oidDTO.setValue("new_value");
}
As result the test is pass because expected and actual are equals. It's equals because in the method changeOidDTO
I change value.
Nice.
Now another test:
@Test
public void change_object_by_ref() {
OidDTO oidDTO = new OidDTO("init_value");
changeOidDTO(oidDTO);
String expected = "new_value";
String actual = oidDTO.getValue(); // Why no NPE
assertEquals(expected, actual);
}
private void changeOidDTO(OidDTO oidDTO) {
oidDTO = null;
}
And test is fail.
expected: <new_value> but was: <init_value>
Expected :new_value
Actual :init_value
As you can see I set null in this line:
oidDTO = null;
The question is: Why not throw NPE in the next line:
String actual = oidDTO.getValue()
?
Solution
You asked why no NPE on this line
String actual = oidDTO.getValue(); // Why no NPE
Because oidDTO
is not null.
OidDTO oidDTO = new OidDTO("init_value");
This line
changeOidDTO(oidDTO);
Changes the LOCAL variable oidDTO
, and not the original one being passed to the function.
Answered By - hfontanez