A method’s declared return type must match the type of value used in the return statement.

Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Return Type

  • Article
  • 08/03/2021
  • 2 minutes to read

In this article

The return type of a function establishes the size and type of the value returned by the function and corresponds to the type-specifier in the syntax below:

Syntax

function-definition:
    declaration-specifiersopt attribute-seqopt declarator declaration-listopt compound-statement

/* attribute-seq is Microsoft-specific */

declaration-specifiers:
    storage-class-specifier declaration-specifiersopt
    type-specifier declaration-specifiersopt
    type-qualifier declaration-specifiersopt

type-specifier:
    void
    char
    short
    int
    __int8 /* Microsoft-specific */
    __int16 /* Microsoft-specific */
    __int32 /* Microsoft-specific */
    __int64 /* Microsoft-specific */
    long
    float
    double
    signed
    unsigned
    struct-or-union-specifier
    enum-specifier
    typedef-name

The type-specifier can specify any fundamental, structure, or union type. If you do not include type-specifier, the return type int is assumed.

The return type given in the function definition must match the return type in declarations of the function elsewhere in the program. A function returns a value when a return statement containing an expression is executed. The expression is evaluated, converted to the return value type if necessary, and returned to the point at which the function was called. If a function is declared with return type void, a return statement containing an expression generates a warning and the expression is not evaluated.

The following examples illustrate function return values.

typedef struct
{
    char name[20];
    int id;
    long class;
} STUDENT;

/* Return type is STUDENT: */

STUDENT sortstu( STUDENT a, STUDENT b )
{
    return ( (a.id < b.id) ? a : b );
}

This example defines the STUDENT type with a typedef declaration and defines the function sortstu to have STUDENT return type. The function selects and returns one of its two structure arguments. In subsequent calls to the function, the compiler checks to make sure the argument types are STUDENT.

Note

Efficiency would be enhanced by passing pointers to the structure, rather than the entire structure.

char *smallstr( char s1[], char s2[] )
{
    int i;

    i = 0;
    while ( s1[i] != '\0' && s2[i] != '\0' )
        i++;
    if ( s1[i] == '\0' )
        return ( s1 );
    else
        return ( s2 );
}

This example defines a function returning a pointer to an array of characters. The function takes two character arrays (strings) as arguments and returns a pointer to the shorter of the two strings. A pointer to an array points to the first of the array elements and has its type; thus, the return type of the function is a pointer to type char.

You need not declare functions with int return type before you call them, although prototypes are recommended so that correct type checking for arguments and return values is enabled.

See also

C Function Definitions

Feedback

Submit and view feedback for

A method's declaration provides a lot of information about the method to the compiler, to the runtime system, and to other classes and objects. Included is not only the name of the method, but also such information as the return type of the method, the number and type of the arguments required by the method, and which other classes and objects can call the method.

While this may sound like writing a novel rather than simply declaring a method, most method attributes can be declared implicitly. The only required elements of a method declaration are the method's name, its return type, and a pair of parentheses ( ). This figure shows the elements of a method declaration.

A method’s declared return type must match the type of value used in the return statement.
Each element of a method declaration is further defined below: accessLevel As with member variables, you control which other classes have access to a method using one of four access levels: public, protected, package, and private. Controlling Access to Members of a Class covers access levels in detail. static As with member variables, static declares this method as a class method rather than an instance method. Understanding Instance and Class Members talks about declaring instance and class methods. abstract An abstract method has no implementation and must be a member of an abstract class. Refer to Writing Abstract Classes and Methods for information about why you might want to write an abstract method and how such methods affect subclasses. final A final method cannot be overridden by subclasses. Writing Final Classes and Methods discusses why you might want to write final methods, how they affect subclasses, and whether you might want to write a final class instead. native If you have a significant library of functions written in another language such as C, you may wish to preserve that investment and use those functions from Java. Methods implemented in a language other than Java are called native methods and are declared as such using the native keyword. Check out our
A method’s declared return type must match the type of value used in the return statement.
LINKFILE ../../native1.1/index.html ) trail for information about writing native methods. synchronized Concurrently running threads often invoke methods that operate on the same data. These methods may be declared synchronized to ensure that the threads access information in a thread-safe manner. Synchronizing method calls is covered in Doing Two or More Tasks at Once: Threads
A method’s declared return type must match the type of value used in the return statement.
. Take particular note of the section entitled Synchronizing Threads
A method’s declared return type must match the type of value used in the return statement.
. returnType Java requires that a method declare the data type of the value that it returns. If your method does not return a value, use the keyword void for the return type. Returning a Value from a Method talks about the issues related to returning values from a method. methodName A method name can be any legal Java identifier. You need to consider several issues in regards to Java method names. These are covered in Method Names. ( paramlist ) You pass information into a method through its arguments. See the next section, Passing Information into a Method. [throws exceptions] If your method throws any checked exceptions, your method declaration must indicate the type of those exceptions. See Handling Errors with Exceptions
A method’s declared return type must match the type of value used in the return statement.
for information. In particular, refer to Specifying the Exceptions Thrown by a Method
A method’s declared return type must match the type of value used in the return statement.
.

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 operator to return the value. Any method that is not declared void must contain a return statement. The Stack class declares the isEmpty method, which returns a boolean:
public boolean isEmpty() {
    if (items.size() == 0)
        return true;
    else
        return false;
}
The data type of the return value must match the method's return type; you can't return an Object type from a method declared to return an integer. The isEmpty method returns either the boolean value true or false, depending on the outcome of a test. A compiler error results if you try to write a method in which the return value doesn't match the return type.

The isEmpty method returns a primitive type. Methods also can return a reference type. For example, Stack declares the pop method that returns the Object reference type:

public synchronized Object pop() {
    int len = items.size();
    Object obj = null;
    if (len == 0)
        throw new EmptyStackException();
    obj = items.elementAt(len - 1);
    items.removeElementAt(len - 1);
    return obj;
}
When a method returns an object such as pop does, the class of the returned object must be either a subclass of or the exact class of the return type. This can be a source of confusion, so let's look at this more closely. Suppose you have a class hierarchy where ImaginaryNumber is a subclass of java.lang.Number, which is, in turn, a subclass of Object, as illustrated here:
A method’s declared return type must match the type of value used in the return statement.
Now suppose 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 some other type. You also can use interface names as return types. In this case, the object returned must implement the specified interface.

Java supports method name overloading so that multiple methods can share the same name. For example, suppose you are writing a class that can render various types of data (strings, integers, and so on) to its drawing area. You need to write a method that knows how to render each data type. In other languages, you have to think of a new name for each method, for example, drawString, drawInteger, drawFloat, and so on. In Java, you can use the same name for all of the drawing methods but pass a different type of parameter to each method. So, in your data rendering class, you can declare three methods named draw, each of which takes a different type of parameter:

class DataRenderer {
    void draw(String s) {
        . . .
    }
    void draw(int i) {
        . . .
    }
    void draw(float f) {
        . . .
    }
}
Overloaded methods are differentiated by the number and type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types. You cannot declare more than one method with the same name and the same number and type of arguments because the compiler cannot differentiate them. So, draw(String s) and draw(String t) are identical and result in a compiler error.

A class may override a method in its superclass. The overriding method must have the same name, return type, and parameter list as the method it overrides. Overriding Methods shows you how to override methods.

When methods must share data you can pass the data into and return?

When methods must share data, you can pass the data into and return the data out of methods. A method could be called using any numeric value as an argument, whether it is a variable, a named constant, or a literal constant. A method's return type is part of its signature.

What are methods with identical names that have identical parameter lists but different return types?

If a class has multiple methods having same name but parameters of the method should be different is known as Method Overloading.

What happens when you call a method and the method ends?

A variable declared within a method ceases to exist when the method ends. It goes out of scope. A method can also return "nothing" also known as a void method. A method can return a value when it ends.

Is a measure of the strength of the connection between two program methods?

In computer programming, cohesion refers to the degree to which the elements inside a module belong together. In one sense, it is a measure of the strength of relationship between the methods and data of a class and some unifying purpose or concept served by that class.