1

I am looking for a way in Java to allow a return statement to compile like so:

public void void1(){
  return;
}

public void void2(){
  return void1();   // compile error here
}

is there a way in Java to return a call on the same line if it's void? I end up having to do this of course:

   public void void2(){
      void1();   
      return;
   }
Naman
  • 27,789
  • 26
  • 218
  • 353
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 1
    why you need return on void method?, and i will suggest to explain the use case as well – Ryuzaki L Feb 07 '19 at 04:20
  • 1
    `return; void1();` although the readability is reduced. However, in your specific case `void1();` would do the same thing (no need for `return`) – MadProgrammer Feb 07 '19 at 04:20
  • `void` wont return anything.... – Vishwa Ratna Feb 07 '19 at 04:20
  • 1
    This is likely an [XY Problem](http://xyproblem.info/) where you ask how to solve a specific code problem when the best solution is to use a completely different approach. Better that you tell us the overall problem that you're trying to solve rather than how you're currently trying to solve it. – Hovercraft Full Of Eels Feb 07 '19 at 04:22
  • @HovercraftFullOfEels just trying to reduce verbosity and put return on the same line. probably very slight perf penalty but less verbose. Mostly aesthetic/readability. – Alexander Mills Feb 07 '19 at 05:05
  • Trying to write code that fights against the known structure of the language will only *reduce* readability, not improve it – Hovercraft Full Of Eels Feb 07 '19 at 05:12
  • @HovercraftFullOfEels that's probably true (but look at lambdas :) .... `(() -> out.println("hmmmm"));` – Alexander Mills Feb 07 '19 at 05:24

1 Answers1

3

is there a way in Java to return a call on the same line if it's void

Yes, you can return on the same line: void1(); return;

But there's no way to return in the same expression: return void1();

erickson
  • 265,237
  • 58
  • 395
  • 493