Friday 13 March 2020

Java: Can a non-void method compiles, run without return value

Yes, we can make a non-void method to run without return value.

Example
int infiniteLoop(){
         while(true) {
                  .....
         }
}

In the above example, compiler knows that the loop will never terminate and no need of return value.

App.java
package com.sample.app;

import java.util.concurrent.TimeUnit;

public class App {

 private static int infiniteLoop() throws InterruptedException {
  int count = 0;
  while (true) {
   System.out.println(++count);
   TimeUnit.SECONDS.sleep(5);
  }
 }

 public static void main(String args[]) throws InterruptedException {
  infiniteLoop();

 }

}


Output

1
2
3
....
....
....


You may like

No comments:

Post a Comment