I saw like in Java there is no pass by reference. But for the below two scenarios, which one is better?
1.
public static void main(String args[]) {
CarDto car = new CarDto();
method1(car);
//do something with car
}
private void method1(CarDto car) {
car.setName("BMW");
}
2.
public static void main(String args[]) {
CarDto car = method2();
//do something with car
}
private CarDto method2() {
CarDto car = new CarDto();
car.setName("BMW");
return car;
}
As per my understanding, method 1 is better than method 2. In method 1, only one CarDto object is created. In method 2, there are two CarDto object created.
Please clarify.