Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

java - "Variable may not have been initialized"

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

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

void edit(String str){
    str = "hallo";
}

My compiler says that it "may not have been initialized".

Can someone explain this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 
}


}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...