Why does this Method script work. Java

public class Main {
  static int myMethod(int x, int y) {
    return x + y;
	System.out.println(myMethod(x, y));
  }

  public static void main(String[] args) {
     myMethod(5, 3);
  }
}

When I run the program this error appears:

Main.java:4: error: unreachable statement
System.out.println(myMethod(x, y));
^
1 error

Hi welcome to the forums. Two things:

  1. Java is not JavaScript, those are two different programming languages, I’ve changed the category.
  2. Anything after the return statement in the method isn’t going to be reachable the function is done at that point. And the thing you’re trying to call is the function itself, so if that code was reachable it would call itself, which would call itself, which would call itself and so on infinitely.

Also, I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Hi HegemoneXT,
myMethod will end just after the return, so println() will never be reached!

If you call, instead, println() from the main function, it will correctly print the returning value of myMethod. Have a look here:

public class Main {
  static int myMethod(int x, int y) {
    return x + y;
  }

  public static void main(String[] args) {
	System.out.println(myMethod(x, y));
  }
}
1 Like