Using variables outside of an if-statement

后端 未结 2 2047
甜味超标
甜味超标 2020-12-04 00:08

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?

相关标签:
2条回答
  • 2020-12-04 00:44

    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";
    }
    
    0 讨论(0)
  • 2020-12-04 01:02

    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";
    }
    
    0 讨论(0)
提交回复
热议问题