There is such a method:

public static void asd(){ return; int x = 20; System.out.println(x); } 

IDE (watched in netbins and eclipse) swears at the inaccessibility of the code after return;

Imgur

but if you change the return; on if (true) return;

 public static void asd(){ if(true) return; int x = 20; System.out.println(x); } 

NetBeans IDE stops swearing, and Eclipse simply displays the varning, and the compiler swallows the whole thing.

Imgur

Question: why so? )) Thank

  • just checking IDE unreachable statement - Gorets
  • 3
    The second version of the people received the name "Hindu code" :) - aleksandr_mai
  • @impe, If you are given a comprehensive answer, mark it as correct (click on the check mark next to the selected answer). - Deleted

2 answers 2

In this case, you argue as a person. It is obvious to a person that in both situations only the return will be executed.

However, from the point of view of the compiler is not so simple. The fact is that the compiler does not have the right to make decisions for the user, he has the right only to prompt him. In the first case, the code is obviously erroneous - the code after return will never be completed. Therefore, here the compiler can signal an error.

However, in the second case, everything is not so simple - although the condition is always true, the compiler cannot know whether it is written by mistake or the user really wants it (for example, this condition may be a stub for some if, which will be implemented later ). Given that the compiler cannot know what the user wants and is not entitled to make decisions for him, in this situation he can only warn about a possible error.

  • Yes, everything is logical and rightly said) ATP - impe
  • You can also replace the value of true with false by reflex and the code after the condition will work. - Deadkenny

It's not entirely clear why this is so complicated. The void methods do not return values. return terminates the void method at the moment it appears, in your case, at the very beginning. "if (true) return" will always cause the return to execute and the method to terminate, i.e. the rest of the method body will still be the dead code. If it was necessary to return the value of a variable for further use and at the same time output its value to the console, the solution will be as follows:

 public static void main(String[] args) { int a = asd(); System.out.println(a); } public static int asd() { int x = 20; return x; } 

If, however, simply output to the console, then the following:

  public static void asd(){ int x = 20; System.out.println(x); } 
  • It is absolutely not about what the vehicle wants to achieve in the code. And about why the IDE and the compiler can swear only on the simplest cases of unreachable code, keeping silence with the slightest complications. - D-side