I want to exit from a function if length of a string( originalPath.length) is equal to some specific number and this is restriction as well I cant do any other thing any idea?
String original = originalPath.substring(0, originalPath.length() - separatorPos);
this snippet is part of a function and not loop.
Make a void method and then
You can do it using if condition and return statement like
if(condition){
return;
}
return is used to stop further execution and return any value back from where it was called.
There are other options like throwing exceptions for the same and break,continue for loops in java
You can use return; if your method is a void, otherwise just return a default value like return false to finish your method if the condition fails.
The return statement will finish your method.
Related
I have a method that handles different error codes and always throws unchecked exception. This method is used in many places across the class. When I try to call it inside another method that has not void return type as shown below:
public Object someMethod() {
....
if(success){
return result;
} else {
callMethodThatAlwaysThrowsUncheckedExceptions();
}
}
java compiler says that the method is missing return statement.
Only two options come to my mind how to solve this problem:
replace method call with its content
add a return statement just after method call that returns an empty object
However I don't really like any of these options: the first one because of code duplication and the second one because of the need to write code that will never be executed.
Is there any other way to solve this problem?
Just swap around the terms, you'll never get to return if the method throws.
if(!success){
callMethodThatAlwaysThrowsUncheckedExceptions();
}
return result;
Or even
callMethodThatAlwaysThrowsUncheckedExceptions(succes);
return result;
Just check the success condition in your throwing method.
Next to the great answer already provided by Slawomir Chodnicki, here's another suggestion.
Change your callMethodThatAlwaysThrowsUncheckedExceptions() which somewhere throws an Exception into a factory method. E.g: change this:
// somewhere in callMethodThatAlwaysThrowsUncheckedExceptions
throw new MyException();
To:
return new MyException();
That way you can call that method like this:
throw callMethodThatAlwaysThrowsUncheckedExceptions();
And thus will help the compiler to see that this is the last statement of that execution branch.
This also works greatly with different exceptions, just return instead of throw
To indicate that you don't expect a line to be reachable (after your call to the throwing method) you can
throw new AssertionError("comment to your co-developers why this never gets reached")
I like minus's answer, but it can be a bit unreadable to users that might mistakenly think return result; will always be executed (regardless of the value of success).
As an alternative, you can change
void callMethodThatAlwaysThrowsUncheckedExceptions () {}
to
Object callMethodThatAlwaysThrowsUncheckedExceptions () {}
(no need to change the method body).
Now you can write
public Object someMethod() {
....
if (success) {
return result;
} else {
return callMethodThatAlwaysThrowsUncheckedExceptions();
}
}
None of the answers above matched my taste of programming. The closest match that I found is here. Inspired from this linked answer, I handled such missing return statement errors in the following way:
First making the return type of the method same as that of exception which it always throws
MyCustomRuntimeException callMethodThatAlwaysThrowsUncheckedExceptions() {
// ....
throw new MyCustomRuntimeException();
}
Next whenever we have to fail the method execution, simply call above method and throw it
public Object someMethod() {
// ....
if (success) {
return result;
} else {
throw callMethodThatAlwaysThrowsUncheckedExceptions();
}
}
This can be used even in methods having void return type without explicitly mentioning the throw keyword. Ofcourse in such places some IDEs may warn of UnusedReturnValue but that can be suppressed as well.
Basically I have a if..else logic as below
if(request.getParameter("action")=="delete" && request.getParameter("action")!=null)
{
//delete operation
}
else
{
//update operation
}
But during update process "action" parameter do not get attached with URL and hence NullPoitnerException is thrown.
Any solution to fix it?
Thanks in advance!
If your request.getParameter(x) returns null when x is not set, you could simply swap the two conditions in your if-clause.
Thus
if(request.getParameter("action")=="delete" && request.getParameter("action")!=null)
would become
if(request.getParameter("action")!=null && request.getParameter("action")=="delete")
Since && is a short-circuit Boolean And in Java, this will cause the the second half of the statement to be executed only if the part before the && evaluates to true - thereby preventing your NullPointerException.
request.getParameter("action")=="delete" is a comparison with a string literal, though. You are most likely better off using .equals() instead.
In Java 8 you can do like this
Optional<String> paramOptional=Optional.ofNullable(request.getParameter());
paramOptional.ifPresent(param->{
//Do something with param
});
OR
String param =paramOptional.orElse("you else string");//if null then this string will be return
Given the following Java code, how can I use the IntelliJ or Eclipse debugger to return false from the condition() method?
public boolean condition() {
return (4 == add());
}
public int add() {
return 2 + 2;
}
In Eclipse you can use Force Return.
Just place a breakpoint on return (4 == add()); and type false on the Display view-tab. Then make a selection of your false, right click and hit "Force Return".
In IntelliJ (since IDEA 15 EAP) you can use Force return.
Extract from jetbrains' blog
You can force the return from the current method without executing any more instructions from it:
NB :
If the method returns a value, you’ll have to specify it (smart code completion provided).
If the method has try-finally blocks, you’ll be able to choose whether to execute them or not.
You can first change the code for condition to something like this:
public boolean condition() {
boolean result = (4 == add());
return result;
}
Then, you can set a breakpoint on the return statement. When the breakpoint is hit, you can use the debugger to change the value of result to false.
Can Anyone explain me how this code works.
// Method returns null if bitmap not available
public Bitmap getBitMap(long id) {
for ( Bitmap item : myBitmaps.keySet() ) {
if ( item != null) {
if ( item.getId() == id ) {
return item;
}
}
}
return null;
how come its possible to use two return (including one inside if block) in a function.sorry I am new to java.
Simple.
The first return statement returns the item only if the two nested conditions are satisfied.
Once your loop is over (aka the two nested conditions are not satisfied), the second return statement triggers and returns null.
In short, if your myBitmaps array or Collection contains a Bitmap that is not null and whose id equals the given id for the method, that Bitmap instance is returned.
Otherwise, null is returned.
As fge mentions, a method has to fulfill all possible return paths (save for exceptional conditions).
If null was not returned outside your loop, the code would not compile.
This would happen because if your conditions were not fulfilled, your loop would terminate without returning anything, and so would your method.
When a return statement is called the function exits. You can have multiple return statements on different places because you might want to return different values depending on what happened in the function.
At a time only one return works. When return item executes it actually returns the control to the statement line from where this method was called. In this case return null will not get execute. And when For loop executed whole and nothing happened at that time return null statement will get execute.
So at a time only one return statement will get execute, no matter if there is more than one return statements in a method.
Basically there are 3 steps:
Loop every Bitmap presents in myBitmaps
If the bitmap is 'valid' (means not null) continue. Otherwise, let's iterate to the next Bitmap.
If the id is the one you were looking at, return the Bitmap.
So what it does is: Get the Bitmap with the specified id if it exists.
the if condition should be like this:
if ( item != null && item.getId() == id){
return item;
}
This is how I understand method getUser below :
Return a User object or null
Get a Set of users and assign them to userSer.
If the set is not empty begin iterating over the set but
return the first user within the set.
Here is the method :
private User getUser(UserDet arg)
{
Set<User> userSet = arg.getUsers(User.class);
if (CollectionUtils.isNotEmpty(userSet))
{
for (User user : userSet)
{
return user;
}
}
return null;
}
I think I could replace the method with this :
private User getUser(UserDet arg)
{
Set<User> userSet = arg.getUsers(User.class);
if (CollectionUtils.isNotEmpty(userSet))
{
return userSet.iterator().next();
}
else {
return null;
}
}
This new method removes the loop and just returns the first element in the set, same as original implemention. Is it correct?
Yes. Actually, it's pretty much almost the same thing, as a foreach loop is syntactic sugar for using an iterator from an Iterable.
Note, however, that you don't need the nonempty check in the first variant, since the loop won't iterate in the case of an empty set anyway.
yes both are same. in first implementation, control will return on first iteration of the loop from the function and consequently loop will end.
Yes it is correct, I'd even go for removing the CollectionUtils.isNotEmptySet and use the Iterator's hasNext method... If the set is guaranteed to be non-null.
It seems to be correct, but it will only make the method a bit easier to read, it will not optimize it in terms of performance. Still I think the change is good and you should do it.
Yes, it does pretty much the same, but if your spec says to start iterating then maybe you should - maybe this method will be extended in the future.
BTW: it is a good convention that your method has only one return statement (i.e. you can create a variable, which will be returned, assigned a null at the beginning and assign a user inside your loop)
Yes. Both the methods return the first element in the set. The first method seems to have been written for something else previously and changed then keeping the for loop intact.
In anycase, the second method that you're proposing won't give any significant performance benefit but should be a better way than the first one.
So in case, UserDet#getUsers(Class) never returns null (but an empty Set in case no user could be found), the shortest (and in my opinion most readable) form is:
private User getUser(UserDet arg) {
Set<User> userSet = arg.getUsers(User.class);
return userSet.isEmpty() ? null : userSet.iterator().next();
}
I would do this.
I won't run a loop and more over I'l add a null check.
private User getUser(UserDet arg) {
Set<User> userSet = arg.getUsers(User.class);
if (userSet != null && userSet.size() > 0) {
return userSet.iterator().next();
}
return null;
}