1

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.

skmaran.nr.iras
  • 8,152
  • 28
  • 81
  • 116
  • 1
    People marking this as a duplicate : The OP is *not* asking if Java is pass by value or pass by reference. He already knows that. He is asking about which approach is better. It may be an opinion based question. But duplicate? Not really. Please take a few seconds to understand a question and improve it. If you feel it's impossible to improve it, then go ahead and close it for the right reasons. – Chetan Kinger Jun 23 '15 at 07:10
  • 1
    Does your second method even compile? –  Jun 23 '15 at 07:12
  • I would rather to use option1. You create an object from Class CarDto and later assing the value to the method. Making a clear and easy code – carlos gil Jun 23 '15 at 07:14
  • You second method wont compile, void methods cant return values – carlos gil Jun 23 '15 at 07:17
  • Is better for what? Performance, code readabilty, maintenance? – fantarama Jun 23 '15 at 07:17
  • second method has been fixed.. anyway, I would go for method 1 as it is better to read the code. – dly Jun 23 '15 at 07:18
  • 1
    It really depends on the context. For example if your method name is `setCarName()` then first method would be appropriate. If it's `getBMWCar()` then second would be appropriate. – Codebender Jun 23 '15 at 07:19
  • @Arvind I edited the question to fix the compilation error – skmaran.nr.iras Jun 23 '15 at 07:20
  • Where is the second object created with method 2? – Keppil Jun 23 '15 at 07:24
  • Really? This is a duplicate of *Is Java pass by reference or pass by value*? How? Can the users who voted to close this as a duplicate speak up? – Chetan Kinger Jun 23 '15 at 10:18

0 Answers0