end the method that call this method - java

Is there a way to end the method that calls on the method that the code is in. Let me explain if you have some code like this.
int value;
value = method();
value = 3;
If I got it work like I want then the execution of the code would end on line 2 and line 3 would never be executed. basically it would be like there was a return between line 2 and 3. Is is something like this possible with Java?
Edit: Ok i think a lot of people have misunderstood me. The code that end the code on in this method on line 2 should be inside of method() and it should not be possible to avoid this outside this method if it's call inside of a try for example.

Your example is a bit abstract, a real one might result in better answers. In general though there are two ways this is normally achieved:
Return a special value e.g. -1
int method() {
if (/* something is wrong */) {
return -1;
}
// Process as normal and return real value
}
...
int value;
value = method();
if (value == -1) {
value = 3;
}
Throw an exception in method()
int method() throws IllegalStateException {
if (/* something is wrong */) {
throw new IllegalStateException();
}
// Process as normal and return real value
}
...
int value;
try {
value = method();
} catch (IllegalStateException e) {
value = 3;
}

You can terminate the current program / JVM with System.exit
java.lang.System.exit(0 /* Status */ );
If you don't want to exit then you have to use return.
in a void method do
int value;
value = method();
return;
Or if method has the same return signature as the current method
int value;
return value = method();

Add if condition value=youexpected return;

Related

How to check a boolean method return value in java

I am pretty new to Java what I am trying to do may seem really strange but it is a matter of me understanding a little bit about how Java works more than actually accomplishing a set result.
If I have a boolean method for instance:
public class doThings
{
// imagine the intial value of this variable is set
// and or modified using getters and setters between the declaration
// and the following method
private boolean boolVar;
public boolean doSomething()
{
if(boolVar == true)
{
//does things and then returns true
return true;
}
else
{
return false;
}
}
}
And I want to call this method in another class like so...
public class testDoThings
{
doThings someObject = new doThings;
public static void main(String[] args)
{
someObject.doSomething()
}
}
How do I check (in the class testDoThings) to see if the method has returned true or returned false and print messages accordingly something like this...
public class testDoThings
{
doThings someObject = new doThings;
public static void main(String[] args)
{
someObject.doSomething()
if (doSomething() returns true) // yes I am aware this is not
//valid
{
// print a statment
}
else if (doSomething() returns false) // yes once again not valid
{
// print a different statement
}
}
}
I am aware that you could put these messages in the class containing the method but if I want different messages depending on where the method is called and what it is a called on then putting things in the original class method is not always going to work.
If I am completely off the track here please let me know, if someone can explain this to me though, that would be great!
You can try like this:
if (someObject.doSomething()) //So if your function returns true then the below statement will be executed
{
// print a statment
}
else //This will check for the false condition of your function
{
// print a different statement
}
You can try something like this:
if(someObject.doSomething()){
System.out.print("foo1");
}
else{
System.out.print("foo2");
}
Here's one way:
if(someObject.doSomething() == true){
System.out.print("foo1");
}
else{
System.out.print("foo2");
}
Generally you compare two things using == operator: if (x == y) ... so we have:
if ( someObject.doSomething() == true ) {
//statements
} else {
//statement for the case where result of method call is false
}
BTW instead of if(x == true) you can simply write if(x).
Conditional structures like if, while, do..., etc receive a boolean value, so it isn't necessary to put "boolVar == true". Just doing "if (boolVar)" is enough. As for your example in the doSomething method, just doing "return boolVar;" would do the work, without the need of any ifs, unless you pretend to do some more things on it.
To check a function return value works in the same way. I mean, variables have a value and functions also, the only difference is that variables hold a value while functions calculate or generate a value. So, in your code:
public class testDoThings {
public void check() {
doThings someObject = new doThings();
boolean flag = sameObject.doSomething();
if (flag) {
// print a statment
} else {
//If you want to check falsehood, !flag would do.
// Notice the "!" sign before
// the flag variable?
// It is a NOT sign, so
// NOT true = false
// NOT false = true
// The if will execute its code
// When the result value is true
// So when the function return val is
// false.
// print a different statement
}
}
}
I hope this explanation is enough clear.

How to make sure a piece of code runs before a method exits

I have a method with if-else cases, and more than one return statement, depending on the exact flow.
I have one line of code that needs to happen just before the return statement (e.g. releaseResources).
I want to be sure that this line is executed no matter what.
Is there a nice way of doing that in java?
Something that will make sure a piece of code is executed before leaving a closure?
What you are looking for is a try-finally block. Here is an example:
public Something someMethod() {
try {
if(someStatement) {
return new Something();
} else {
return new SomethingElse();
}
} finally {
// this is always executed, even if there is an Exception
}
}
The question is if this is really what you want. It sounds like your code might actually be better (more readable) if it has two methods. Like this:
public Something createSomething() {
if(someStatement) {
return new Something();
} else {
return new SomethingElse();
}
}
public Something someMethod() {
Something something = createSomething();
// Do the thing that always needs to be done
return something;
}
This separates the things you are doing into two methods. Now if the problem is that the first method can throw an exception and you want to do something nonetheless, you can still use a finally. But it might be better to capture and handle the Exception.
Also: You've noted that you want to close a resource. In that case I would suggest you look into try-with-resources:
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
An example here:
private String someMethod() throws IOException {
// Java automatically closes the following Readers:
try (BufferedReader br =
new BufferedReader(new FileReader("/path"))) {
return br.readLine();
}
}
Depending of the programming language you're using, the try-catch-finally exist:
Example from other post about launch code after the if-else
Finally statement will launch when try-catch condition ends
SORRY FOR EDIT
You can use a try/finally block, if that's what you really want.
try {
if (...) return ...;
else if (...) return ...;
else return ...;
} finally {
doSomething();
}
The code in the finally block will always be executed when you leave the try block, in particular at any return statement.
The finally block will always be executed even if an Exception is thrown.
try {
...
if () {
return;
else {
return;
}
} finally {
// Release resources
}
One of the main programming good practices is that each method should have one and only one return statement. If you have many possible values, you tend to keep the value in an object and return it at the end.
E.g:
public int func(boolean condition) {
if(condition) {
return 1;
} else {
return 0;
}
}
should be made like this
public int func(boolean condition) {
int num;
if(condition) {
num = 1;
} else {
num = 0;
}
return num;
}
As you can probably see, it's quite simple to ensure you call your method before return this way, adding it right before the only return.

Why have a return keyword if you're not returning a value?

As I was reading my AP java book I stumbled upon this section that made no sense to me:
...The getBalance method simply returns the current balance. A return statement obtains the value of a variable and exits the method immediately. The return value becomes the value of the method call expression. The syntax of a return statement is:
return expression;
or
return; // Exits the method without sending back a value
Why would you want to have a return statement and "exit the method without sending back a value" if you could just make it void?
***Note: Sorry if this may be too subjective. I just couldn't understand the point and the book doesn't explain it.
The return keyword doesn't need to be at the end. For example:
public static void print42(int[] numbers) {
for(int i=0; i<numbers.length; i++) {
if (numbers[i] == 42) {
System.out.println("has 42");
return;
}
}
System.out.println("no 42");
}
It can't just use a break, as that would print both strings.
This is kind of subjective. I'm old school, I believe in one entry and exit point for all methods/functions, but...
If you have a method with a void return type and if you had reached a point in your logic which would dictate that no further processing should take place, you could call return; to force the execution to return to the calling method at this point, foregoing any further execution of the method.
It would be the same as using something like return x; in the middle of a method body that had an expected return type (of whatever x is)
It's a little like using break to break out of a loop prematurely, except you're breaking out of the method before the execution gets to the end.
There are some situations where once you've verified something inside a void function, it makes sense to exit it immediately. For example:
public static void checkIfStringInList(List<String> searchList, String findString) {
for( String thisSearchString : searchList ) {
if( findString.equals(thisSearchString) )
return;
}
throw new Exception("String " + findString + " not found in list");
}
A method declared as void can exit with a return; this is just a shortcut for early termination. A method with a non-void return type must return a value of the right type, you can not have a method return "nothing" if it has a non-void return type.
If your method has a void return type, then the return statement is optional. You might want to use it anyway if, for instance, you wanted to stop execution in certain cases.
If the return type is not void, then using return; without an argument will give you a compile error.
In java if a method has a return type in its signature, you must return an object of that type or null before exiting the method.
for example
public A foo(boolean val){
A obj=null;
if (val){
obj=new A();
obj.setSomeAttribute();
}
return obj;
}
You can not compile source code if you just code "return;"

calling function should return default value, if object (or any function result) is null

Is it possible to wrap following code in a reusable function?
EDIT: this is just an example, I want a working solution for ALL recursion depths
what I want is that following code is generated:
if (MyObject o == null ||
o.getSubObject() == null ||
o..getSubObject().getSubSubObject() == null /*||
... */)
return defaultValue;
return o.getSubObject().getSubObject()/*...*/.getDesiredValue();
by calling something like
Object defaultValue = null;
Object result = NullSafeCall(o.getSubObject().getSubObject()/*...*/.getDesiredValue(), defaultValue);
The seond code block is just an idea, I don't care how it looks like, all I want is that I, if desired, can avoid all the null checks before calling a deeper function...
Injection could do this propably, but is there no other/easier solution? Never looked at injection before yet...
EDIT2: example in another language: http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator
Not really, any code you would write this way would look horrible and/or use very slow reflection. Unless you use an actual Java preprocessor that can understand and change the code you've written.
A better (but associated with quite a bit of refactoring) approach would be to make sure that the values in question cannot possibly be null. For example, you could modify the individual accessors (getSubObject(), getDesiredValue()) to never return null in the first place: make them return default values. The accessors on the default values return default values in turn.
Java8 helps to get the closest you'll get to your syntax with decent performance I suspect;
// Evaluate with default 5 if anything returns null.
int result = Optional.eval(5, o, x->x.getSubObject(), x->x.getDesiredValue());
This can be done with this utility class;
class Optional {
public static <T, Tdef, T1> Tdef eval(Tdef def, T input, Function<T,T1> fn1,
Function<T1, Tdef> fn2)
{
if(input == null) return def;
T1 res1 = fn1.apply(input);
if(res1 == null) return def;
return fn2.apply(res1);
}
}
Sadly, you'll need a separate eval() defined per number of method calls in the chain, so you may want to define a few, but compile time type safe and reusable with just about any calls/types.
You can do something like this
public static Object NullSafeCall(MyObject o,Object defaultValue){
if ( o == null || o.getSubObject() == null)
{
return defaultValue;
}
else
{
return o.getSubObject().getDesiredValue();
}
}
Now you can call this method as follows
Object result = NullSafeCall(o, defaultValue);
i would suggest just replace
Object result = NullSafeCall(o.getSubObject().getDesiredValue(), defaultValue);
by the
Object result = (o == null || o.subObject == null) ? defaultVlue : o.getSubObject().getDesiredValue();
Create method only if you can reuse it......
What you want is not possible. It is essential to understand that using this syntax: Object result = NullSafeCall(o.getSubObject().getSubObject() ...); the part of o.getSubObject().getSubObject() will be evaluated before any control passes to the function/method thus throwing the exception.
It is required to have some type of context before executing such code. The closest to this I could think of, can be done using anonymous inner classes like the example below:
// intended to be implemented by an anonymous inner class
interface NullSafeOperation<T> {
public T executeSafely();
};
// our executor that executes operations safely
public static class NullSafeExecutor<T> {
public NullSafeExecutor() {}
public T execute(T defaultValue, NullSafeOperation<T> nso) {
T result = defaultValue;
try {
result = nso.executeSafely();
} catch(NullPointerException e) {
// ignore
}
return result;
}
// utility method to create a new instance and execute in one step
public static <T> T executeOperation(T defaultValue, NullSafeOperation<T> nso) {
NullSafeExecutor<T> e = new NullSafeExecutor<T>();
T result = e.execute(defaultValue, nso);
return result;
}
}
public static void main(String[] args) {
final String aNullString = null;
String result = NullSafeExecutor.executeOperation("MyDefault", new NullSafeOperation<String>() {
#Override
public String executeSafely() {
// trying to call a method on a null string
// it will throw NullPointerException but it will be catched by the executor
return aNullString.trim();
}
});
System.out.println("Output = " + result); // prints: Output = MyDefault
}

Which will be returned in a program

I was wondering what will be returned in a java program when you have multiple returns in a program.
private int numberReturner()
{
if (a) return a;
else if (b) return b;
for (int i = 1; i < board.size()-1; i++)
{
if (c) return c;
}
return d;
}
So lets say a is true, (it should return a), but wouldn't it return d because that is the final line of code in the whole program? Why is this so?
Sorry if I worded this a bit strangely...
Once any 'return' statement is encountered the method will exit execution and return that value.
That method will return d only if no other return statement is encountered before reaching that last line.
Normally, the first "return" encountered will be the one returned. But if there is a "return" statement encountered in a finally block, the "return" in the finally block will be returned.
e.g.
private int m1(){
try{
return 1;
}finally{
return 2; //this will be returned instead
}
}
If you've already "returned" you are never going to hit the subsequent returns.
The method returns a because the return statement exits from the current method, and control flow returns to where the method was invoked. Please read more about different branching keywords in Java tutorial. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
Once a return statement is executed the method ends and if it is not void the return value is returned.
I know only one exception to this rule, and you have it with the finally statement.
Take this example:
public static void main(String[] args) {
System.out.println(test());
}
private static int test() {
try {
return 1;
} finally {
return 2;
}
}
in this case test() returns 2, because the finally statement in this case is always executed before exit the method.
The current execution thread will leave a method the first time it encounters a return statement (the notable exception to this rule is with try...finally blocks, where, once a return is encountered, the finally{...} block executes before leaving the method.

Categories