“Variable may not have been initialized”

前端 未结 4 556
陌清茗
陌清茗 2020-12-22 02:42

I\'ve got a method that creates a String and another method that changes Strings

void create(){
    String s;
    edit(s);
    System.out.printl         


        
相关标签:
4条回答
  • 2020-12-22 03:00

    Variable may not have been initialized

    As you define the s inside a method you have to init s in it somewhere every variable in a program must have a value before its value is used.

    Another thing not less important, your code won't never work as you expected cause Strings in java are inmutable then you cannot edit your String, so you should change your method edit(Str s).

    I Change your code to something like this but i think your edit method should do another thing rather than return "hallo".

    void create(){
        String s=null;
        s =edit(); // passing a string to edit now have no sense
        System.out.println(s);
    }
    // calling edit to this method have no sense anymore 
    String edit(){
        return "hallo"; 
    }
    

    Read more about that java is passed by value in this famous question : Is Java "pass-by-reference"?

    See this simple Example showing that java is passed by value. I cannot make an example with only Strings cause Strings are inmutable. So i create a wrapper class containing a String that is mutable to see differences.

    public class Test{
    
    static class A{
     String s = "hello";
    
     @Override
     public String toString(){
       return s;
     }
    
    }
    
    public static void referenceChange(A a){
        a = new A(); // here a is pointing to a new object just like your example
        a.s = "bye-bye";
    }
    
    public static void modifyValue(A a){
       a.s ="bye-bye";// here you are modifying your object cuase this object is modificable not like Strings that you can't modify any property
    }
    
    public static void main(String args[]){
       A a = new A();
       referenceChange(a);
       System.out.println(a);//prints hello, so here you realize that a doesn't change cause pass by value!!
       modifyValue(a);
       System.out.println(a); // prints bye-bye 
    }
    
    
    }
    
    0 讨论(0)
  • 2020-12-22 03:15

    try to initialize the string "s" to a null value, since you have declared a variable "s" but it has not been initialized. Hence it can't pass the reference of that variable while used as parameter.

    String s = null;
    

    Hope this helps

    0 讨论(0)
  • 2020-12-22 03:21

    Give your variable S a value or as Jeroen Vanneve said "Change it to String s = null;"

    0 讨论(0)
  • 2020-12-22 03:22

    You declare local variable s in method create, so that you need to initialized it before you use it. Remember that java does not have default value for local variable. Init String s = "" or whatever value than your code will run normally.

    0 讨论(0)
提交回复
热议问题