1

Does it make any difference whether I create an object, store it, then call a method, and directly calling the method with (new object).method?

String s=sc.nextLine();
String[] ss=s.split(" ");//1st method

String[] ssnew=(sc.nextLine()).split(" ");//2nd method

Doing this for a coding contest with hidden test cases, 1 out of 7 test cases doesn't pass when using the second method, but all 7 pass while using the first method. There is no input before or after this, only a print statement.

Mathamagic
  • 97
  • 9
  • 2
    No difference. You will just not have any object reference for future use. and object will be available for garbage collector. – SSP Sep 30 '19 at 05:18
  • some differences: 1) 2 lines of code instead of one; 2) use of an additional variable; 3) consequence of 2: eventually harder to debug (to check created instance) – user85421 Sep 30 '19 at 05:58

1 Answers1

1

There is no difference between the 2 ways. But in the first way you can still have the reference of the input String for further processing.

Sujay Mohan
  • 933
  • 7
  • 14
  • 1
    First method also adds to the readability of your code. – rootExplorr Sep 30 '19 at 05:20
  • Second method is more readable if you drop the braces around `sc.nextLine()`. – Johannes Kuhn Sep 30 '19 at 05:51
  • I know there is supposed to be no difference, but the contest gives 7(hidden) test cases for the problem, and only changing from the second method to the first method for scanning the input(there is no input before or after this, just 1 output integer) takes my score from 6 test cases passed to 7 test cases passed. – Mathamagic Sep 30 '19 at 18:28
  • but as mentioned by @Carlos Heuberger there is a additional variable in the first case and in second case you can remove the additional ().less overhead in memory. – Sujay Mohan Sep 30 '19 at 18:32