简体   繁体   中英

Java Void Methods Return

Java: Why is a method called void (ie. it doesn't return anything) if it returns this:

System.out.println("Something");

For example:

public static void sayHello() {
        System.out.println("Hello");
}

It does return something, this message!

我会说它会将消息打印到标准输出,但不会向调用语句返回任何内容。

This method does something (prints "Hello"), but it doesn't return anything. If it returned a value, you'd be able to do this:

aVariableToAssignReturnValue = sayHello(); //you can't do it!

Read this for example.

Consider these two routines.

public void sayHello() { System.out.println("Hello"); }

public int giveANumber() { System.out.println("Hi"); return 42; }

How would you call them?

sayHello();
int i = giveANumber();

Since sayHello is void, there's no equals sign and nothing on the left-hand side when you call it. However, since giveANumber returns an int, you should call it with the equals sign and an integer to receive the value on the left-hand side.

In programming language history there was Algol68, possibly the best procedural language of all. It was the first fully defined language, and everything was typed. It was so to say and expression language.

In it VOID was a type with a single value SKIP. A PROC () VOID, a method, could be coerced to VOID, doing a call.

It doesn't return anything that can be stored in variable .

so it's simply don't return anything.

but it can do things like print to console.

"Return" in this case means that a value is passed back through the stack that could be assigned to a variable in the calling code. That's not the case in your example.

Object o = sayHello(); // WRONG - Compile error

A void method can do things - In your case print to the screen. That's not a "return" in these described here.

Since the question shows at the top of the page as "Java Void Methods Return" with a capital "V" on "Void" it may also be worth noting that Java has a class "Void" in addition to the keyword "void." A method declared to return Void does return something - but if that's your case, you should check the documentation for that class because it's kind of a special case.

It's simple and straightforward because you are asking him to execute something not returning something . your method returns a void which means nothing. Being ac programmer, In C a method that returns nothing is called procedure. for more checkout What is the difference between a "function" and a "procedure"? .

sayHello() has no return statement; therefore, it is a void method. By your assumption, the only truly void method would look like this: public static void wowSuchVoid(){ } . What's even the point?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM