Return statement function in if conodition - java

In my code:
if (id.isEmpty() || name.isEmpty()) {
warlbl.setText("Warning, Empty ID or Name Fields");
return;
}
id and name are String that give from JTextFields ,
Is necessary use return; in here or Not?

Yes, it can be:
if (...) {
...
return;
}
// nothing at this point will be reached if the if-statement is entered
vs.
if (...) {
...
}
// code here will still be reached!

return exits the current method you are "in".
Of yource it is not necessary but maybe you want to exit the method if id.isEmpty() and name.isEmpty(). So no and yes. It is not neccassary but you may want to return
You can use return to break out of a method, continue to skip a loop or a break to break out of a block.
Often there are 2 ways:
public void test() {
if (!statement) {
// to something if statement is false
} else {
//we failed, maybe print error
}
}
or:
public void test() {
if (statement) {
//we failed, maybe print error
return;
}
//do something if statment is false
}
But this is more a kind of "style". Mostly I prefere the second way, just because it's less spagetti :P
Keep in mind. If your return statement would be the last statment executed it's redundant.
Java reference:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

Related

while(true) loop only executes once

I wrote a piece of code which should be executed until the condition is satisfied. I have 2 classes using the same structure. In one of them while (true) loop executes as expected; in the other class the program exits the loop after the first recursion.
protected static boolean flag = true;
private static int value=0;
private static int limit=10;
.
.
.
public static int method(){
if (limit-value <=0)
{
...
}
else {
while(flag) {
if (limit-value > 0 ) {
*the action I want to perform until the condition is satisfied*
value++;
}
else if (limit==value)
{
flag = false;
}
return int_Value;
}
}
}
return int_Value;
}
I expect the while(true) loop to be executed until the condition is satisfied (which is more than once).
With some cleaned up indentation it becomes clear that the while loop contains an unconditional return.
if you look at your code the while loop goes like this
while(flag) {
if (limit-value > 0 ) {
*the action I want to perform until the condition is satisfied*
value++;
}
else if (limit==value)
{
flag = false;
}
return int_Value;
}
after executing either if or if else statement there is a return int_value statement which is causing the problem
Although I did debugging I couldn't see it in the first place. I performed another debug session after #user3437460 's suggestion, so I was able to find out:
It seems like an additional return statement was used!(return int_Value;),
the one after else if block. So, the program returns a value and never goes back into the loop.
After deleting the first return statement, program runs just fine.

If-then-else statement use

Method: “run”
Create endless loop
If MerkleManager.sMerkleRoot is not null then...
If the above merkle root equals the initial user-entered merkle root.Then print out “You win: “ followed by the merkle root and exit the app.
Else if they’re not equal, then tell the user he lost – and exit the app.
My code:
public void run() {
while (true) {
}
if MerkleManager.sMerkleRoot = null;
{
} else {
}
System.exit(0);
}
How do I set MerkleManager.sMerkleRoot not null and use if-then-else statement?
In your check you are assigning the value of MerkleManager.sMerkleRoot with "=" assignment operand.
Instead you should be checking "==" or "!=" operand to compare the object references.
public void run() {
while (true) {
}
if MerkleManager.sMerkleRoot != null
{
} else {
}
System.exit(0);
}
Your code will never leave the while loop the way it's written.
Change to this,
public void run() {
while (true) {
if MerkleManager.sMerkleRoot != null{
// do stuff
}else {
// do something else
}
System.exit(0); // if you leave this statement, your code will exit on the first exec
}
First off, you are saying that you want it to exit the JVM whether the condition is met or not which would render the while loop useless as the first iteration would guarantee a termination for either case (and the way you have it currently will get you stuck in the loop and never execute the following line anyways) so you can remove that completely.
Second, you need parentheses around the boolean statement in an if clause in java.
What you want to do for your method might look a little more like this
public void run() {
if (MerkleManager.sMerkleRoot != null && MerkleManager.sMerkleRoot == inputRoot) {
System.out.println("You won");
}
else {
System.out.println("You lose");
}
System.exit(0);
}

Do i also need to return string outside if-else condition ,when the return type is String

The compiler keeps telling to return string.I used if-else condition and from within if-else i have returned string.The compiler problem will be solved if i put return statement at the end of the code but my problem will start .I dont understand how to solve this problem.I want to return right when its right.
Code:
public String isValidID(String id) {
if(getId().length()!=6) {//checks for 6 digit id
return "wrong";
}
else{//checks if digit contains invalid entry
for(int i=0;i<getId().length();i++){
if(Id.charAt(i)>'9'||Id.charAt(i)<'0')
return "wrong";
}
}
}
In reply to my comment to add return "right" at the end, you said:
but that will make the program return "right " always.Becoz after if-else condition check ,the compiler will execute rest statement and will return "right" always
Now the source of your confusion is clear: return doesn't just set the value the method will return, it also exits the method, immediately. So for instance, the return "wrong"; inside your loop will exit from the loop, and the method, immediately. This is true of all the languages I've seen that use the return keyword (whereas there are some languages, like VB/VB.Net, where you assign a value to the function's name to set the return value, but execution continues normally until you use "exit").
That's why adding return "right"; at the end is how you resolve this, because the code won't reach that point if it ever reached return "wrong"; during the program flow above it:
public String isValidID(String id) {
if(getId().length()!=6) {//checks for 6 digit id
return "wrong"; // <== Exits immediately if reached
}
else{//checks if digit contains invalid entry
for(int i=0;i<getId().length();i++){
if(Id.charAt(i)>'9'||Id.charAt(i)<'0')
return "wrong"; // <== Exits immediately if reached
}
}
return "right"; // <== Exits immediately if reached
// (granted, we would have exited
// below anyway :-) )
}
In any condition, you need to return "something". In your code it possible that return never executed in a certain condition. Suppose your program execution comes to if(Id.charAt(i)>'9'||Id.charAt(i)<'0') and it never gets true then what the method will return? So, You need to write the code in a manner that in condition method execution will execute a return statement which returns a String object.
Just imagine a conditon Suppose
1. getId().length()!=6 -> false
2. getId().length() is 0
3. for(int i=0;i<getId().length();i++) will never enter the loop.
Then what should the method returns when you call it.
If I can understand your logic you can just use :
public String isValidID(String id) {
return id.matches("\\d{6}") ? "correct" : "wrong";
}
You check the length if it is 6 or not then you check if all characters are digits, you can combine both of them in one instruction, just check if the input is a number with length 6 with regex.
If you want a clean solution use boolean instead of a String in this case you can use :
public boolean isValidID(String id) {
return id.matches("\\d{6}");
}
Inside your else you have another if statement, so your return its not always reached. You need another return after the for cycle.
And you are checking if something is wright or wrong you should return Boolean true or false.
public boolean isValidID(String id) { if(getId().length()!=6) {//checks for 6 digit id return false; }
else{//checks if digit contains invalid entry for(int i=0;i'9'||Id.charAt(i)<'0') return false; }
return true;// when nothing false was found.
}
}
So in your case, I would have done public boolean isValidID instead.
Here, the compiler tells you to return something in case the length of the ID is not correct and the components of the ID (so the caracters) are between 0 and 9 (for example if your ID is something like 00ggg89, then I suppose it is wrong, but if your ID is 000000, then it could be right. Here is what I would have done
public boolean isValidID(String id) {
return id.matches("[0-9]{6}");
}
Hope this helps ! :D
public String isValidID(String id) {
String result = "right";
if(getId().length()!=6) {//checks for 6 digit id
result = "wrong";
}
else{//checks if digit contains invalid entry
for(int i=0;i<getId().length();i++){
if(Id.charAt(i)>'9'||Id.charAt(i)<'0')
result = "wrong";
}
}
return result;
}
Edit: In case the first statement is not valid it will never get to a return statement. Thats why you have to return a String in every possible case.

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.

Categories