Void as Return Type

Can someone explain a void return type in Java?

Can someone explain a void return type in Java?

The void type is used to declare that a method does not return a value.

Couldn't you just make the return type String and set the string equal to the parameter to make it show up when the method is called?

Hypothetically "you" (or in this case, the designers of the PrintStream API) could do that, but there is no point in doing it. I am struggling think of a plausible use-case where it would make sense to use the println argument String ... if it was returned as a result.

Bear in mind the primary goals of a good API design include1:

  • to support the common use-cases well, and
  • to be easy for programmers to understand.

Methods that return values that either don't make sense or that are rarely (if ever) used are (IMO) poorly designed.

If the void return type method has other methods in it could you make the return type method which would return the outcome of that method?

Well, I guess so. But you've got the same issues as above. If the result is either rarely used or is hard to understand (and therefore hard to use correctly) then it is probably bad design to return it.

When is it that you could only use the void return type?

One case is where you are implementing or overriding a method in an interface or a superclass, and that method is declared with a void return type.

But in isolation, there are no cases where you can only use void. (But there are lots of cases where good design says that it is best to use void!)


1 - There other goals too. Please don't take this out of context ...

Why Typescript return type void in interface doesn't trigger error in implementation?

The inferred type of the method without the explicit type declaration is HumanOne.speak(): string. This is compatible with void, which has two meanings:

  • in a function implementation with return type void, it means that it doesn't return anything, more or less equivalent to specifying undefined as a return type.
  • in a function type declaration, void means that anything can be returned, and that the return value of calls must not be used. It's more or less equivalent to unknown as far as type compatibility is concerned (but unlike unknown, you can't really pass around values of type void).

This second meaning is also what is relevant for the subtype checking of HumanOne implements Person - the type () => string is a subtype (or: assignable to) type () => void. If you call Person.speak(), you must ignore the return value (and it might be undefined, a string, or anything else); if you call HumanOne.speak() you'll know that you get a string back.

This is very much by design, see the docs on Return type
void
and the FAQ entry "Why are functions returning non-void assignable to function returning void?".

What does void mean as the return type of a method?

Return type is what you get out of it. When you call it, what are you hoping to get back? For instance, if the method gets the average of two numbers, then you're expecting a number back, so the return type will be a number type, like "int" (integer).
You can see what it should be using that logic or by looking in the method for the word return - what comes after return is what is returned, and its type should be declared in the method (e.g. if it says "return 4;" it's returning an int, and should be e.g. public int getFour()

You also asked about e.g. testing() vs testing(word)
I remember having the same difficulty. The distinction between the two also relates to the method declaration line. I'll illustrate.

    public String testing(){
return "a word";
}

Calling this method by doing "System.out.println(testing());" should print "a word". Calling this method by doing "System.out.println(testing("a word"));" will give you an issue - this is because when you call testing, it looks at the appropriate method: one in the right class, with the right return type and with the right arguments/parameters. If you're calling testing("a word"), that means you're using a String as an argument (because "a word" is a string), and so it tries to use the testing(String aString) method - which doesn't exist.
So you use empty brackets when the method takes no input, and you put stuff in brackets when the method expects stuff. This should be less confusing than it sounds, because it's usually logical - if you want to call a method that returns an average, you need to ask yourself "Average of what?" You'd probably need to supply it with the values you want the average of.

Moving on: (a) testing() versus(b) AClass.testing() versus(c) aclass.testing() -

In (a), there's no class specified. Therefore, if you call it from that class, Java can guess which class: this one, and it'll work. From any other class, it won't know what you're talking about, and might even insult you.
In (b), you're specifying a class in general - therefore it'll know what class to find it in - and it'll work if it's a "static method". *[see bottom]
In (c), you're specifying an instance of AClass you want to run "testing()" on*.

For instance, imagine you've created a class called Business. You make a hundred Business objects by specifying for each a name, number, address.
e.g.

   Business b = new Business(name, number, address);

Then in the Business class you have a method "getName()". This method takes no argument - you could see that the brackets are empty - so if, from another class, you call "Business.getName()", how could it know which name you want? You've just made a hundred businesses!
It simply can't. Therefore, for such a method, you'd call "b.getName()" (b being the Business we created above) and it would get the name for this instance of a Business - namely, b.
I'm happy to help, so if you're confused about any particular parts of what I just wrote please let me know and I'll try to elaborate!

edit: A bit on static methods:
Static methods don't belong to an instance of the class. getName(), for example, would get the name of this Business - ie, this instance of the Business class. But let's say that in the Business class you made a method that took the first letter of each word in a String and transformed it to uppercase - like if you wanted to make the business names look more professional when you printed them out.

public static String stringToUpperCase(String aString){
aString = aString.substring(0, 1).toUpperCase() + aString.substring(1);
return aString;
}

And to use that, you change the getName() method from:

public String getName(){
return name;
}

to

public String getName(){
return stringToUpperCase(name);
}

The new method is used here to make the name have an uppercase first letter - but that is the extent of its involvement with the Business class. You notice it doesn't ask for information about the name, address, or number for a particular business. It just takes a string you give it, does something to it, and gives it back. It doesn't matter whether you have no Businesses or a hundred.
To call this method, you'd use:

System.out.println(Business.stringToUpperCase("hello"));

This would print Hello.
If it were not a static method, you'd have to make a new Business first:

Business b = new Business("aName", "aNumber", "anAddress"); 

System.out.println(b.stringToUpperCase("hello"));

And if the method did need access to more Business-instance information (like a business's name number or address) it wouldn't be able to be an instance variable.

On Void return type

Void is a class like any other, so a function returning Void has to return a reference (such as null). In fact, Void is final and uninstantiable, which means that null is the only thing that a function returning Void could return.

Of course public void blah() {...} (with a lowercase v) doesn't have to return anything.

If you're wondering about possible uses for Void, see Uses for the Java Void Reference Type?

Using void return type and take in an array of integers as a parameter

Try

using System;

namespace ConsoleApp7
{
class Program
{
public static void Main(string[] args)
{
int[] NewArr = new int[10];
enterNum(ref NewArr);
//trying to change number of array
printSum(NewArr);
//getting sum from array established in Main
}

public static void enterNum(ref int[] args)
{
Console.Write("Enter the slot: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the new value: ");
int y = Convert.ToInt32(Console.ReadLine());
args[x] = y;
return;
}
public static void printSum(int[] args)
{
int sum = 0;
for (int b = 0; b < 10; b++)
{
sum += args[b];
}
sum /= 10;
Console.WriteLine(sum);
return;
}
}
}

Also the line:

sum /= 10;

is going to calculate the average, not the sum.

What does Void return type mean in Kotlin

Void is a plain Java class and has no special meaning in Kotlin.

The same way you can use Integer in Kotlin, which is a Java class (but should use Kotlin's Int). You correctly mentioned both ways to not return anything. So, in Kotlin Void is "something"!

The error message you get, tells you exactly that. You specified a (Java) class as return type but you didn't use the return statement in the block.

Stick to this, if you don't want to return anything:

fun hello(name: String) {
println("Hello $name")
}

Return void type in C and C++

C11, 6.8.6.4 "The return statement":

A return statement with an expression shall not appear in a function whose return type is void.

No, you may not use an expression, even if it is of void type.

From the foreword of the same document:

Major changes in the second edition included:

[...]

  • return without expression not permitted in function that returns a value (and vice versa)

So this was a change from C89 -> C99 (the second edition of the language standard), and has been that way ever since.


C++14, 6.6.3 "The return statement":

A return statement with an expression of non-void type can be used only in functions returning a value [...]
A return statement with an expression of type void can be used only in functions with a return type of cv
void; the expression is evaluated just before the function returns to its caller.

Yes, you may use an expression if it is of void type (that's been valid since C++98).

Void as return type

Edit:

A new separate RFC for a void return type has been published, has passed the vote, and was implemented in PHP 7.1.

There is now a void return type in PHP. :)

Original Post:

Taken from wiki.php.net:

Future Work


Ideas for future work which are out of the scope of this RFC include:

  • Allow functions to declare that they do not return anything at all (void in Java and C)

So currently there is no way to declare that you don't return anything.

I don't know what's best in your situation, but I'd probably just go with not declaring the return type for now.

To answer your question whether there will be a void return type in PHP 7:

There is no guarantee yet, but I think it is very likely that void or a synonym will be implemented in some way.



Related Topics



Leave a reply



Submit