How do I use the “return” keyword in Java?

The return keyword is used to return from a method when its execution is complete. When a return statement is reached in a method, the program returns to the code that invoked it.

A method can return a value or reference type or does not return a value. If a method does not return a value, the method must be declared void and it doesn’t need to contain a return statement.

If a method declare to return a value, then it must use the return statement within the body of method. The data type of the return value must match the method’s declared return type.

package org.kodejava.example.fundamental;

public class ReturnDemo {

    public static void main(String[] args) {
        int z = ReturnDemo.calculate(2, 3);
        System.out.println("z = " + z);

        Dog dog = new Dog("Spaniel", "Doggie");
        System.out.println(dog.getDog());
    }

    public static int calculate(int x, int y) {
        // return an int type value
        return x + y;
    }

    public void print() {
        System.out.println("void method");

        // it does not need to contain a return statement, but it
        // may do so
        return;
    }

    public String getString() {
        return "return String type value";

        // try to execute a statement after return a value will
        // cause a compile-time error.
        //
        // String error = "error";
    }
}

class Dog {
    private String breed;
    private String name;

    Dog(String breed, String name) {
        this.breed = breed;
        this.name = name;
    }

    public Dog getDog() {
        // return Dog type
        return this;
    }

    public String toString() {
        return "breed: " + breed.concat("name: " + name);
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

2 Comments

  1. I know that || is an or operator when used in an if else, but what about a single | when used in a return? I’ve looked everywhere, but it seems like a single | is completely ignored by google’s search engine đŸ˜¡

    Here’s an example:

    return removeHalfBit(k) | (flag ? 8 : 0) | (flag1 ? 16 : 0) | (flag2 ? 32 : 0);
    
    Reply
    • Hi Nick,

      The |, &, ^ are logical operators, but they can also be used as a bitwise operators. As bitwise operators they compare two variables bit by bit and return a variable whose bits have been set based on whether the two variables being compared had respective bits that were either both on (&), one or the other on (|), or exactly one on (^). On means 1 while off means 0.

      For example:

      int a = 10;    // 1010 (binary)
      int b = 5;     // 0101
      int c = a | b; // 1111
      int d = a & b; // 0000
      

      More:

Leave a Reply