-1

if you have an if(boolean && otherBoolean) statment, and the first boolean is false, will Java check the otherBoolean anyway? What I'm thinking is having something like this:

if( text.length()>=4 && text.subString(0,4).equals("~yay") ){ 
//do stuff
}

because the subString method will throw an error if text is less then 4 characters long, I feel like I need to have two if statements

if(text.length()>=4){
  if(text.subString(0,4).equals("~yay"){
   //do stuff
}}

but that is very ineffective to do. I suppose I could write a method, something like

public boolean beginsWith(String text, String replace){
   if(replace.length()>text.length()){return false;)
   if(text.subString(0,replace.length()).equals(replace)){return true;} 

   return false;

I know I could just use that, but I really just want to know if I can use the first option.

Carson Graham
  • 519
  • 4
  • 15

2 Answers2

3

Actually

if (a) {
    if (b) {
        //stuff
    }
}

Is the same thing as

if (a && b) {
    //stuff
}

Debugger will stop verification if a is false. But in more complex statements you should be careful using short circuits.

ivanjermakov
  • 1,131
  • 13
  • 24
2

In Java, the && 'short-circuits' - that is, as it's going along the conditionals it's evaluating, it'll jump out at the first 'false' conditional.

So, your statement will be safe, because you'll need to have at least four characters in order for your code to hit the second conditional.

Marshall Conover
  • 855
  • 6
  • 24