Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables outside of an if-statement

I'm not entirely sure if this is possible in Java, but how would I use a string declared in an if-statement outside of the if-statement it was declared in?

like image 908
KrazyTraynz Avatar asked Nov 12 '12 02:11

KrazyTraynz


People also ask

Can you declare variables in an if statement?

Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared.

How do you use a variable outside of an if statement in PHP?

Right now $uname is only in scope within the if statement, once you leave the if statement the variable no longer exists. PHP has no block scope for variables, so they are available until the end of the function once they have been assigned a value.

Are variables declared inside of an IF block visible outside of the if statement?

Yes. It is also true for for scope.

Can variables be declared outside a class?

If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class. class Geek: # Variable defined inside the class.


1 Answers

You can't because of variable scope.

If you define the variable inside an if statement, than it'll only be visible inside the scope of the if statement, which includes the statement itself plus child statements.

if(...){
   String a = "ok";
   // a is visible inside this scope, for instance
   if(a.contains("xyz")){
      a = "foo";
   }
}

You should define the variable outside the scope and then update its value inside the if statement.

String a = "ok";
if(...){
    a = "foo";
}
like image 98
resilva87 Avatar answered Sep 29 '22 09:09

resilva87