Java method return type void

returning a Void object

What is the correct way to return a Void type, when it isn’t a primitive? Eg. I currently use null as below.

interface B < E method(); >class A implements B < public Void method()< // do something return null; >> 

i’m writing an interpreter for a file format, using the interpreter pattern, but some expressions don’t have return values

There’s no way to instantiate the Void type, so if you really have to return something of that type, null is your only option. However, you probably don’t need the returned value for anything, so null should be fine.

7 Answers 7

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

So any of the following would suffice:

  • parameterizing with Object and returning new Object() or null
  • parameterizing with Void and returning null
  • parameterizing with a NullObject of yours

You can’t make this method void , and anything else returns something. Since that something is ignored, you can return anything.

Java 8 has introduced a new class, Optional , that can be used in such cases. To use it, you’d modify your code slightly as follows:

interface B < Optionalmethod(); > class A implements B < public Optionalmethod() < // do something return Optional.empty(); >> 

This allows you to ensure that you always get a non-null return value from your method, even when there isn’t anything to return. That’s especially powerful when used in conjunction with tools that detect when null can or can’t be returned, e.g. the Eclipse @NonNull and @Nullable annotations.

Читайте также:  Uploading large files with php

My opinion is that this is going in the wrong direction. It is better to return a much more constrained type that conveys the meaning much clearer. Having something that returns an Optional is unnecessary for the same reason that you give, you always get an Optional that is empty and so all the other methods are pointless. This is the opposite of why an optional value should be used. You use it because it may or may not have a value. Also the compiler cannot enforce that method() implements it correctly. This would fail at runtime: return Optional.of(null) .

If you just don’t need anything as your type, you can use void. This can be used for implementing functions, or actions. You could then do something like this:

interface Action  < public T execute(); >abstract class VoidAction implements Action  < public Void execute() < executeInternal(); return null; >abstract void executeInternal(); > 

Or you could omit the abstract class, and do the return null in every action that doesn’t require a return value yourself.

You could then use those actions like this:

private static T executeAction(Action action)
String result = executeAction(new Action() < @Override public String execute() < //code here return "Return me!"; >>); 

or, for the void action (note that you’re not assigning the result to anything)

executeAction(new VoidAction() < @Override public void executeInternal() < //code here >>); 

Why would you have to return anything else? The point I’m trying to make is you don’t need the return value, so it doesn’t matter what you return. I tried to clarify that with my edit.

Just for the sake of it, there is of course the possibility to create Void instance using reflection:

interface B < E method(); >class A implements B < public Void method()< // do something try < ConstructorvoidConstructor = Void.class.getDeclaredConstructor(); voidConstructor.setAccessible(true); return voidConstructor.newInstance(); > catch (Exception ex) < // Rethrow, or return null, or whatever. >> > 

You probably won’t do that in production.

It is possible to create instances of Void if you change the security manager, so something like this:

static Void getVoid() throws SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException < class BadSecurityManager extends SecurityManager < @Override public void checkPermission(Permission perm) < >@Override public void checkPackageAccess(String pkg) < >> System.setSecurityManager(badManager = new BadSecurityManager()); Constructor constructor = Void.class.getDeclaredConstructors()[0]; if(!constructor.isAccessible()) < constructor.setAccessible(true); >return (Void) constructor.newInstance(); > 

Obviously this is not all that practical or safe; however, it will return an instance of Void if you are able to change the security manager.

Источник

Returning a Value from a Method

You declare a method’s return type in its method declaration. Within the body of the method, you use the return statement to return the value.

Any method declared void doesn’t return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:

If you try to return a value from a method that is declared void , you will get a compiler error.

Any method that is not declared void must contain a return statement with a corresponding return value, like this:

The data type of the return value must match the method’s declared return type; you can’t return an integer value from a method declared to return a boolean.

The getArea() method in the Rectangle Rectangle class that was discussed in the sections on objects returns an integer:

// a method for computing the area of the rectangle public int getArea()

This method returns the integer that the expression width*height evaluates to.

The getArea method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this:

public Bicycle seeWhosFastest(Bicycle myBike, Bicycle yourBike, Environment env) < Bicycle fastest; // code to calculate which bike is // faster, given each bike's gear // and cadence and given the // environment (terrain and wind) return fastest; >

Returning a Class or Interface

If this section confuses you, skip it and return to it after you have finished the lesson on interfaces and inheritance.

When a method uses a class name as its return type, such as whosFastest does, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number , which is in turn a subclass of Object , as illustrated in the following figure .

The class hierarchy for ImaginaryNumber

Now suppose that you have a method declared to return a Number :

public Number returnANumber()

The returnANumber method can return an ImaginaryNumber but not an Object . ImaginaryNumber is a Number because it’s a subclass of Number . However, an Object is not necessarily a Number — it could be a String or another type.

You can override a method and define it to return a subclass of the original method, like this:

public ImaginaryNumber returnANumber()

This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.

Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.

Источник

What is the main difference between ‘void method’ and ‘return type method’ in Java? [duplicate]

I have write the code with two methods, one is void (print the string message) and second is return the String. So those two are the almost same, the difference is just return statement in String method. Can anybody explain those two with real life examples?

I don’t understand why this question has been downvoted so many times. As a Java beginner (with not-so-good teachers as it turns out!), I find this question useful because I have the same question myself.

1 Answer 1

I shall try to explain the best I can:

public void printString(String str)

The «void» return type means that this method doesn’t have a return type. It actually doesn’t need one because you «print» your String onto the System’s output stream. In an application, this approach may be used to print runtime specific messages on the console for example.

public String stringMethod(String str)

This other method on the other hand, returns a String. This means that you can use the returned value in your code for further processing. I guess good examples of such methods are «getters». These methods return field values of an object.

For example take the object Person:

import java.lang.String; public class Person < private String name; private String surename; private int age; public Person(String name, String surename, int age) < this.name = name; this.surename = surename; this.age = age; >public String getName() < return name; >public void setName(String name) < this.name = name; >public String toString() < return "Person: " + surename + ", " + name + ". Age: " + age; >public void printPerson() < System.out.println(this.toString()); >> 

Here you can see that the printPerson() uses the toString() method’s returned value to print the result on the output stream.

Источник

What does the return keyword do in a void method in Java?

I’m looking at a path finding tutorial and I noticed a return statement inside a void method (class PathTest , line 126):

if ((x < 0) || (y < 0) || (x >= map.getWidthInTiles()) || (y >= map.getHeightInTiles()))

I’m a novice at Java. Can anyone tell me why it’s there? As far as I knew, return inside a void method isn’t allowed.

8 Answers 8

It just exits the method at that point. Once return is executed, the rest of the code won’t be executed.

public void test(int n) < if (n == 1) < return; >else if (n == 2) < doStuff(); return; >doOtherStuff(); > 

Note that the compiler is smart enough to tell you some code cannot be reached:

I understand your code is illustrative, but for the parent’s info; I’ve worked with people that believe each method should only have a single return statement. I’m not one of them, but do believe in minimizing the number of returns as much as possible without making the code ugly in doing it.

Yeah, it’s definitely not something to overuse, but sometimes it just makes it a lot easier and can still be very readable.

Without a return value return works a lot like break in a loop and simply exits the code in question. There have been many flame wars about multiple exit points from functions and a few languages force you one way or the other. I don’t take a position on multiple exit points, but I will point out that leaving a function cleans up the local stack.

Источник

Оцените статью