KrazyTraynz
KrazyTraynz

Reputation: 101

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?

Upvotes: 10

Views: 64348

Answers (2)

resilva87
resilva87

Reputation: 3465

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";
}

Upvotes: 21

Yanick Rochon
Yanick Rochon

Reputation: 53566

You need to distinguish between a variable declaration and assignment.

String foo;                     // declaration of the variable "foo"
foo = "something";              // variable assignment

String bar = "something else";  // declaration + assignment on the same line

If you try to use a declared variable without assigned value, like :

String foo;

if ("something".equals(foo)) {...}

you will get a compilation error as the variable is not assigned anything, as it is only declared.

In your case, you declare the variable inside a conditional block

if (someCondition) {
   String foo;
   foo = "foo";
}

if (foo.equals("something")) { ... }

so it is only "visible" inside that block. You need to move that declaration outside and assign it a value somehow, or else you will get conditional assignment compilation error. One example would be to use an else block :

String foo;

if (someCondition) { 
   foo = "foo";
} else {
   foo = null;
}

or assign a default value (null?) on declaration

String foo = null;

if (someCondition) {
   foo = "foo";
}

Upvotes: 8

Related Questions