I want to run method x if method y fails. For example
public void createzoo (){
create.chimp();
if
activateByMail.chimp() fails
run
activateByAdmin.chimp()
delete.chimp();
}
It would be good if I could use boolean to accomplish this.
I'm writing scripts in java on ubuntu
return boolean value from chimp() function it something goes wrong in it. and check like
if(!activateByMail.chimp())
activateByAdmin.chimp();
you can do it in these both ways,
1.
make the return type of method1 as boolean, which if fails return false, true otherwise.
boolean method1(){
if(succeed)
return true;
else
return false;
}
//use it like this:
if(!method1()) method2();
2
. if you already have a return value in that method, throw some exception in method 1, and catch it in the call. and in catch block call method2.
void method1(){
if(!succeeed) throw new FailException();
}
use it like this
try{
method1();
} catch(FailException ex){
method2();
}
Related
I am using the Single RxJava object and I want to run a void method in the critical path of the async workflow but return the previous result.
For example, I have something like:
Single<Integer> method() {
Single<Integer> value = Single.just(10);
return value.<RxJava Method>(Consumer<Integer> or Runnable<Integer>);
}
method().blockingGet();
returns
> 10
The stuff I do in Consumer<Integer> or Runnable<Integer>, I want to make sure happens before I return the value 10. Is there a built in method in Single for this?
ie: I am just wondering if there is a cleaner way to portray:
Single<Integer> method() {
Single<Integer> value = Single.just(10);
return value.map(result -> {
// call void method
return result;
});
}
method().blockingGet();
I have recently started experimenting with the return statement, and I have a small doubt relating to it- When I have a method which calls another method, will the return statement of that method which I am calling be displayed?
Let be give an example to make it clearer-
/** Program to test return statment */
public class Test
{
public static void main(int a)
{
EvenOrOdd(a);
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display(As in that window does not pop up with the result.)
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
If I were to simply remove the main method(or even make the second method public and run that directly), my return statement is displayed however if I attempt to call the method and run the program my return statement isn't displayed.
So is this just a problem I am facing or is it a general rule in Java that the return statement doesn't work when you call another method(which has a return statement)?
If it is the latter, then I apologise, I was not aware of this.
Thanks...
***UPDATE***
It seems that nobody has understood what I exactly mean. I will give another example-
Please run this program-:
/** Program to test Return statment;simple program to return sum of two digits */
public class Return_Test
{
public static int main(int a,int b)
{
return a+b;//What I am lloking for is that box in which this is displayed.
}
}
A return statement only returns the value ,does not Display it
If you don’t catch the return value , how can it be displayed? add something like this and try
,
public class Test
{
public static void main(int a)
{
boolean temp=EvenOrOdd(a);
if(temp)
System.out.println("Output is True");
else
System.out.println("Output False(not even )");
//Or you can directly call the method as' System.out.println(EvenOrOdd));'
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
And Please try learning some good Naming Conventions , Classes are Named like this ,
FirstSecond,TestException(Each Word Starts with a Capital Letter) etc , methods start with a small letter , isPrime() , isEven(),
What a lot of other responders don't know is that when you run a method in BlueJ, it executes the method, and if the the return value of the method is non-void, it is shown in a popup dialog by invoking toString. That's what the questioner means by the value being displayed.
The answer to the user's original question is that by surrounding the method with a void return, it "hides" the result. So this code:
public void callMe1(int a)
{
EvenOrOdd(a);
}
will not display the return. But if you adjust the return type and actually return the value of the inner call:
public int callMe2(int a)
{
return EvenOrOdd(a);
}
Then BlueJ will display the returned value. The display aspect is down to BlueJ, but the rules for whether or not the value gets returned are the same as in Java; void means no return.
Within the body of the method, you use the return statement to return the value. It will not print anything on its own.
Changes done - System.out.println(EvenOrOdd(5));
public class Test {
public static void main(String[] args) {
System.out.println(EvenOrOdd(5));
}
private static boolean EvenOrOdd(int a) {// I can declare as public and run directly but then what is the point in
// calling the method?
if (a % 2 == 0) {
System.out.println("The output is true.");// Displays
return true;// Does not display
} else {
System.out.println("The output is false.");// Displays
return false;// Does not display
}
}
}
Output
The output is false.
false
You never actually display the return result from the method...
The name of the method is consuming EvenOrOdd returning true or false is ambigious, may isEven would be better...
You could try something like...
System.out.println(a + " is even = " + EvenOrOdd(a));
You should also avoid using multiple return statements within a single method, it can quickly become confusing as to how the method actually works, in your case, you can reduce the over complexity at the same time, for example...
private static boolean isEven(int a)
{
boolean isEven = false;
if(a%2==0)
{
System.out.println("The output is true.");//Displays
isEven = true;//Does not display
}
return isEven;
}
first change your main signature from main(int a) to main(String [] args) otherwise you will get following runtime exception :
Error: Main method not found in class yourpackagename.Test, please define the main method as:
public static void main(String[] args)
well you didn't print the value return from function :
in your main do this:
System.out.println(EvenOrOdd(5));
Is there a way to identify whether the following method executed completely or returned halfway through(i.e at line no 3)
static int a=0;
static void test(){
if(a>10){
return;
}
a++;
}
The method was invoked by another method.(a might have been changed by it)
I cannot change the method declaration. I am dealing with an object I created from a java file created by someone else. I am not allowed to change the original file
Your method does almost nothing and no there is no way in this example you gave to know if the method returned before complete execution but if you willing to change the function to a boolean type you can return true at complete execution and false at incomplete.
static boolean test()
{
if(a>10)
return false;
a++;
return true;
}
Run the code under debugger like jdb and set the breakpoint on the internal return statement. If the program stops at this breakpoint, this obviously means that it would return through that statement.
To make things more automated, you could try to launch the debugger and control the debugger from a Java program through Runtime. This would make the approach applicable for more use cases, while not for all.
You could use
void test(int a) {
if (a > 10) {
return;
}
a++;
System.out.println("test executed completely!");
}
Or if you want to use the information programmatically
private boolean executedCompletely;
void test(int a) {
executedCompletely = false;
if (a > 10) {
return;
}
a++;
executedCompletely = true;
}
When you use your test method, you can check whether it ran completely this way:
int initialA = a;
test();
int finalA = a;
if (finalA != initialA) {
//a has been changed, therefore the method ran completely
} else {
//a has not been changed, therefore it was not incremented, therefore the method did not run completely
}
I have a question regarding return statements used within if() while() or for() statements.
As you can see in the following method, it is expecting that I return a String value. The problem is that if I were to use a return statement within my if statement block, the compiler would return the error missing return statement.
public String myMethod()
{
if(condition)
{
return x;
}
}
Of course I could change the method header to void and use System.out.println instead of return. But is this the right way to do it? Am I missing something?
If you put a return statement in the if, while or for statement then it may or may not return a value. If it will not go inside these statements then also that method should return some value (that could be null). To ensure that, compiler will force you to write this return statement which is after if, while or for.
But if you write an if / else block and each one of them is having a return in it then the compiler knows that either the if or else will get executed and the method will return a value. So this time the compiler will not force you.
if(condition)
{
return;
}
else
{
return;
}
That's because the function needs to return a value. Imagine what happens if you execute myMethod() and it doesn't go into if(condition) what would your function return? The compiler needs to know what to return in every possible execution of your function.
Checking Java documentation:
Definition: If a method declaration has a return type then there must
be a return statement at the end of the method. If the return
statement is not there the missing return statement error is thrown.
This error is also thrown if the method does not have a return type
and has not been declared using void (i.e., it was mistakenly
omitted).
You can do this to solve your problem:
public String myMethod()
{
String result = null;
if(condition)
{
result = x;
}
return result;
}
That is illegal syntax. It is not an optional thing for you to return a variable. You must return a variable of the type you specify in your method.
public String myMethod()
{
if(condition)
{
return x;
}
}
You are effectively saying: I promise any class can use this method (public) and I promise it will always return a String (String).
Then you are saying IF my condition is true I will return x. Well, that is too bad. There isn't any IF in your promise. You promised that myMethod will always return a String.
Even if your condition is always true, the compiler has to assume that there is a possibility of it being false. Therefore you always need to put a return at the end of your non-void method outside of any conditions just in case all of your conditions fail.
public String myMethod()
{
if(condition)
{
return x;
}
return ""; // Or whatever the default behavior will be if all of your conditions fail to return.
}
Try with, as if the if condition returns false, so it will return empty, otherwise nothing to return.
public String myMethod()
{
if(condition)
{
return x;
}
return ""
}
Because the compiler doesn't know if any of those if blocks will ever be reached, so it's giving you an error.
You have to add a return statement if the condition is false.
public String myMethod() {
if(condition) {
return x;
}
// if condition is false you HAVE TO return a string
// you could return a string, a empty string or null
return otherCondition;
}
FYI:
Oracle docs for return statement
This will return the string only if the condition is true.
public String myMethod()
{
if(condition)
{
return x;
}
else
return "";
}
Anyhow, myMethod() should return a String value. What if your condition is false? - is myMethod returning anything? The answer is no, so you need to define return null or some string value for the false condition:
public String myMethod() {
boolean c = true;
if (conditions) {
return "d";
}
return null; // Or some other string value
}
i wrote an function like
public static boolean check()throws Exception
{
if(a=="asd")
return true;
else
return false;
}
this works fine
but if i use
public static boolean check()
{
try
{
if(a=="asd")
return true;
else
return false;
}
catch(Exception e)
{
}
}
it says you need to return an value,,,, is there is any difference between these two???
you need to return something in the catch, a method always need to return something, even in catch, unless you throw/rethow an exception.
Yes, there is a difference. Your second code block will catch any exception from the if statement and swallow it, and then resume running after the catch block. But there is no return statement there, so if there is any exception, the function will have no return value.
The first code block, on the other hand, uses throws to indicate that Exception descendants may escape from it instead of being caught, so it doesn't need to catch and handle anything itself, and the compiler is prepared to allow the function to not return anything (due to exiting early from an exception).
Java has methods, not functions. So you didn't write a function, but a method. Also, comparing strings with == does not work in Java. You have to call the equals() method instead:
if (a.equals("asd"))
The problem in your second piece of code is this: What happens if an exception occurs? The content of the catch block is executed, and after that the rest of the method is executed. Note that there is no code after the catch block. But the method requires that you return a boolean - you're missing a return statement. Change it like this:
public static boolean check()
{
try
{
if (a.equals("asd"))
return true;
else
return false;
}
catch(Exception e)
{
}
// You need to add a return statement here
return false;
}
There are some more comments that can be made about your code.
First of all, it's always a bad idea to leave a catch block empty. Because when an exception is caught, nothing will happen, and you'll never know that something went wrong. Always handle exceptions appropriately.
Also, code like this:
if (a.equals("asd"))
return true;
else
return false;
can be simplified like this:
return a.equals("asd");
The result of the expression a.equals("asd") is already a boolean; why would you check again if it's true or false and then return true or false?
Not all paths in the code will return a value. Since you have a catch there, if an exception is thrown, no value will be returned because the code in the catch will execute.
I think you should return the value at the end of function after catch. Try to store result in one boolean variable and return that variable after catch. This may solve your problem
A premise:
a=="asd" is not 'wrong' but probably it is better to use a.equals("asd") because == compares pointers, not equality. For example ("asd"=="asd") == false but ("asd".equals("asd")) == false
If if(a=="asd") throws an exception, the flow goes in the catch, and then it exits without ever finding the return statement. the correct code could have a return statement inside the catch block
Jesper's answer pretty much covers it. I needed to show some code so therefore this separate answer.
You will have to decide in each situation how to handle exceptions. Jesper and LordSAK both chose to return 'false'. A problem with this is that you can't distinguish the error condition from the case that 'a' is not equal to "asd".
A possible solution is to change the method's return type to Boolean (the Object version of the primitive boolean) and return 'null' in case of an exception
public static Boolean check() {
try {
return "asd".equals(a);
}
catch(Exception e) {
return null;
}
}
Another option is to re-throw your exception as an unchecked exception:
public static boolean check() {
try {
return "asd".equals(a);
}
catch(Exception e) {
throw new RuntimeException("Problem during check", e);
}
}
A drawback of this approach is that the code calling your check() method does not expect a runtime exception to be thrown. Because this type of exception is unchecked the developer will not get a compiler warning if he doesn't surround the call to check() with try-catch.
A third option is to just declare the exception and let your calling code handle it. A full example:
import org.apache.log4j.Logger;
public class Checker {
private static final Logger LOG = Logger.getLogger(Checker.class);
private String a;
public Checker(String value) {
a = value;
}
public boolean check() throws Exception {
return "asd".equals(a);
}
public static void main(String[] args) {
Checker app = new Checker("Stackoverflow");
try {
app.check();
}
catch(Exception e) {
LOG.error("Problem during check", e);
}
}
}
An advantage is that you don't have to decide which value check() returns in case of an error, but instead you just return the error itself. This is actually the whole idea of 'throwing' exceptions.
As a rule of thumb: if you can't handle an exception within the method itself, then throw it and let the calling code deal with it.
An example from the wild: A method handling an exception itself.
private static final long DEFAULT_TIMEOUT = 60000;
public long getTimeout(String timeoutArg) {
try {
return Long.parseLong(timeoutArg);
}
catch(NumberFormatException e) {
return DEFAULT_TIMEOUT;
}
}
NB: I didn't compile or run any of this code, so there might be typos.