java - Void methods can't return the value of a void method? -


i don't mind if don't understand, want know why happens:

void something(string a) {     return hi(); } void hi() {     return; } 

the odd thing here, hi() has return type of void. syntax error in ide:

void methods cannot return value 

furthermore, code doesn't compile:

exception in thread "main" java.lang.error: unresolved compilation problem:      void methods cannot return value      @ resources.setsystemproperties(resources.java:33)     @ resources.main(resources.java:49) 

i expect happening:

hi() -> return nothing  return [nothing] -> hi() nothing 

so in end, returns nothing, void method should.

why behaviour happen? , why doesn't code compile, when return result of void method?

this defined in jls 14.17:

a return statement expression must contained in 1 of following, or compile-time error occurs:

  • a method declared return value
  • a lambda expression

a void method not declared return value, return statement expression (like function call) cannot happen in such method.

additionally, can't return result of void method due language in jls 15.12.3:

if compile-time declaration void, method invocation must top level expression (that is, expression in expression statement or in forinit or forupdate part of for statement), or compile-time error occurs.

in other words, since a.notify() void, can use in contexts looks statement (ie, alone on line) not in contexts looks expression (ie, can't assign value variable, return it, etc).


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -