bouncingHippo
bouncingHippo

Reputation: 6040

Continue Statement in a Java Function

I want to create logic such that: if s2 is null the debugger skips all the complex string manipulation and returns null instead of s1 + s2 + s3 as seen in the first if block. Am I wrong somewhere?

public static String helloWorld(String s1, String s2, String s3){
   if(s2==null){
     continue;
     return null;
   }

   ... lots of string manipulation involving s1, s2 and s3.

   return (s1+s2+s3);
}

Upvotes: 2

Views: 2110

Answers (3)

F. Mayoral
F. Mayoral

Reputation: 175

don't use continue there, continue is for loops, like

for(Foo foo : foolist){
    if (foo==null){
        continue;// with this the "for loop" will skip, and get the next element in the
                 // list, in other words, it will execute the next loop,
                 //ignoring the rest of the current loop
    }
    foo.dosomething();
    foo.dosomethingElse();
}

just do:

public static String helloWorld(String s1, String s2, String s3){
   if(s2==null){
     return null;
   }

   ... lots of string manipulation involving s1, s2 and s3.

   return (s1+s2+s3);
}

Upvotes: 7

nkr
nkr

Reputation: 3058

You do not need continue there, return null; is enough.

continue is used within loops when you want the loop to skip the rest of the block and continue with the next step.

Example:

for(int i = 0; i < 5; i++) {
    if (i == 2) {
        continue;
    }

    System.out.print(i + ",");
}

Will print:

0,1,3,4,

Upvotes: 2

Brian
Brian

Reputation: 17309

The continue statement is used for loops (for, while, do-while), not for if statements.

Your code should be

public static String helloWorld(String s1, String s2, String s3){
   if(s2==null){
     return null;
   }

   ... lots of string manipulation involving s1, s2 and s3.

   return (s1+s2+s3);
}

Upvotes: 2

Related Questions