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);
}
}
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
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:
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
means1
whileoff
means0
.For example:
More:
Different Types of Methods Declaration based on Return type and Arguments: Return types in Java
I don’t get what the use of return is. Why can’t we just leave it and have the method automatically return whatever value is obtained by the instructions in the block that is the method body? Were is it useful for a method NOT to return something? And if that is never the case, why bother with return at all? Why not have it be implied.
Your article provides a good and very detailed explanation about return . Thanks for sharing good post . Keep it up .