Why is this code giving an “unreachable code” error?

喜你入骨 提交于 2019-11-27 14:33:21

Once you return from a method, you return to the method that called the method in the first place. Any statements you place after a return would be meaningless, as that is code that you can't reach without seriously violating the program counter (may not be possible in Java).

jambriz

Quoting a comment on the question by Jim H.:

You returned from the pop() method. Anything after that is unreachable.

Unreachable code results in compiler error in Java.

In your program the line

int count2 = 0;

will never be reached since it is after the return statement.

Place this line above the return statement to work.

The simple explanation in plain English would be the following:

 private Object pop(){
    return myStack[0];
    int count2 = 0; //Unreachable Code
} 

method private Object pop(){} is looking for a return type Object and you just gave that return type by writing return myStack[0]; .So your method does not necessarily reach int count2 = 0; because it assumed that the method already reached its goal.

Declare before return myStack[0] that fixes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!