Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something after return statement - Java

Tags:

java

soap

The requirement is below.

I have a Electrical chargeable vehicle (device) which communicates to a java application (service) via SOAP message. When the device is switched on, It sends a request to the service through SOAP message.

The service receives the SOAP message request and checks whether the device is authorized device (we check this from database where we have few authorized devices details stored) or not. If the device is authorized, then the service respond to the device via Accepted or Rejected SOAP message.

When the service sends the SOAP response to the device, after 5 SECONDS, the service has to send a SOAP request to the device asking the device settings.

Below is the sample code from the service.

public AuthorizeResponse authorize(AuthorizeRequest parameters) {
   AuthorizeResponse authorizeResponse = new AuthorizeResponse();

   //check from db whether the device is authorized or not from 
    parameters.getDeviceName();

   return authorizeResponse; 
}

Now, the requirement is, after "return authorizeResponse;", I have to do Thread.sleep(5000) and send a request from the service to the device.

Can anybody help me in this regard how to do?

like image 724
Vijayakumar Avatar asked Mar 15 '14 16:03

Vijayakumar


People also ask

Can we write anything after return statement in Java?

We cannot write any code after return statement. If you are trying to compile with this code, compilation will fail. It is same for throwing exception. This is because after return or throwing exception statement the control will goes to the caller place.

What happens after return statement in Java?

In Java programming, the return statement is used for returning a value when the execution of the block is completed. The return statement inside a loop will cause the loop to break and further statements will be ignored by the compiler.

Can you put code after a return statement?

The only way you could usefully have code after a "return" is if the "return" statement is conditional. This isn't great coding style, you're creating code where there are 2+ ways to exit. When you need to debug it you'll find it more challenging to put in flags and "what happened when we exited" and so forth.

Does method end after return statement Java?

Yes, it will end the method once a value is returned.


1 Answers

You can use a finally block:

public Integer printAfterReturn() {
    try {
        int a = 10;
        return a + 10;
    } finally {
        System.out.println("printed");
    }
}
like image 101
arshajii Avatar answered Sep 30 '22 12:09

arshajii