Introduction
As we know, Java is an object-oriented programming language. That is, the basic concept, because to say the basis of the fundamentals is that everything is an object. Objects are described using classes.
![Return statement in Java - 1]()
Classes, in turn, have state and behavior. For example, a bank account may have a state in the form of the amount of money in the account and have the behavior of increasing and decreasing the balance. Behavior in Java is implemented using methods. How to describe methods is introduced at the very beginning of your Java learning journey. For example, in the official tutorial from Oracle: “
Defining Methods ”. There are two important aspects here:
- Each method has a signature. The signature consists of the method name and its input parameters;
- Methods must specify a return type;
- The return type is not part of the method signature.
Again, this is a consequence of the fact that Java is a strongly typed language and the compiler wants to understand in advance which types are used where as much as possible. Again, to protect us from mistakes. In general, everything is for the good. Well, this once again instills in us a culture of handling data, it seems to me. So, for methods the value type is specified. And to return this same value from the methods, the keyword is used
return
.
Keyword return statement in Java
The statement keyword
return
refers to "control flow statements" as discussed in the oracle tutorial "
Control Flow Statements ". You can also read about how to return values in the official tutorial: “
Returning a Value from a Method ”. The compiler carefully monitors, to the best of its ability, that the value returned from a method matches the return value type specified by the method.
Let's use the Online IDE from tutorialspoint as an example . Let's look at the original example:
public class HelloWorld {
public static void main(String []args) {
System.out.println("Hello World");
}
}
As we can see, a method is executed here
main
, which is the entry point to the program. Lines of code are executed from top to bottom. Our
main
method cannot return values, otherwise we will receive an error: "
Error: Main method must return a value of type void
". Therefore, the method will simply output to the screen. Let's now move the receiving of the string into a separate method for receiving the message:
public class HelloWorld {
public static void main(String []args) {
System.out.println(getHelloMessage());
}
public static String getHelloMessage() {
return "Hello World";
}
}
As we can see, using the keyword
return
we specified the return value, which we used later in the method
println
. In the description (definition) of the method,
getHelloMessage
we indicated that it will return us
String
. This allows the compiler to check that the method's actions are consistent with the way it is declared. Naturally, the type of the return value specified in the method definition can be broader than the type of the value returned from the code, i.e. The main thing is that the types are reduced to each other. Otherwise we will get a compilation time error: "
error: incompatible types
". By the way, the question probably immediately arose: Why
return
does it apply to program flow control operators? But because it can disrupt the normal flow of the program from top to bottom. For example:
public class HelloWorld {
public static void main(String []args){
if (args.length == 0) {
return;
}
for (String arg : args) {
System.out.println(arg);
}
}
}
As can be seen from the example, we interrupt the execution of the method
main
if our java program is called without parameters. It is important to remember that if you then
return
have the code, it becomes inaccessible. And our smart compiler will notice this and will not allow you to run such a program. For example, this code will not compile:
public static void main(String []args) {
System.out.println("1");
return;
System.out.println("2");
}
There is a dirty hack to get around this. For example, for debugging purposes or for some other reason. The above code can be fixed by wrapping it
return
in
if
a block:
if (2==2) {
return;
}
Return statement in error handling
There is one very tricky circumstance - we can use it
return
in conjunction with error handling. I would like to say right away that using it
return
in
catch
a block is very, very bad form, so you should avoid it. But we need an example, right? Here he is:
public class HelloWorld {
public static void main(String []args) {
System.out.println("Value is: " + getIntValue());
}
public static int getIntValue() {
int value = 1;
try {
System.out.println("Something terrible happens");
throw new Exception();
} catch (Exception e) {
System.out.println("Catched value: " + value);
return value;
} finally {
value++;
System.out.println("New value: " + value);
}
}
}
At first glance, it seems that 2 should be returned, because
finally
it is always executed. But no, the value will be 1, and the change to the variable in
finally
will be ignored. Moreover, if it
value
contained an object and we
finally
said
value = null
, then it
catch
would still return a reference to the object, not
null
. But from the block
finally
the operator
return
would have worked correctly. Colleagues will clearly not thank you for such a gift.
void.class
And finally. You can write a strange construction like
void.class
. It would seem, why and what is the point? In fact, in various frameworks and tricky cases where
the Java Reflection API is used , this may be very necessary. For example, you can check what type a method returns:
import java.lang.reflect.Method;
public class HelloWorld {
public void getVoidValue() {
}
public static void main(String[] args) {
for (Method method : HelloWorld.class.getDeclaredMethods()) {
System.out.println(method.getReturnType() == void.class);
}
}
}
This can be useful in test frameworks where it is necessary to replace the real code of methods. But to do this, you need to understand how this method behaves (i.e., what types it returns). There is a second way to implement the method
main
from the code above:
public static void main (String[] args) {
for (Method method : HelloWorld.class.getDeclaredMethods()) {
System.out.println(method.getReturnType() == Void.TYPE);
}
}
A rather interesting discussion of the difference between them can be read on stackoverflow:
What is the difference between java.lang.Void and void? #Viacheslav
GO TO FULL VERSION