Java: how to initialize String[]?

后端 未结 11 2177
渐次进展
渐次进展 2020-12-22 18:57

Error

% javac  StringTest.java 
StringTest.java:4: variable errorSoon might not have been initialized
        errorSoon[0] = \"Error, why?\"         


        
相关标签:
11条回答
  • 2020-12-22 18:59
    String[] errorSoon = { "foo", "bar" };
    

    -- or --

    String[] errorSoon = new String[2];
    errorSoon[0] = "foo";
    errorSoon[1] = "bar";
    
    0 讨论(0)
  • 2020-12-22 19:02

    String Declaration:

    String str;
    

    String Initialization

    String[] str=new String[3];//if we give string[2] will get Exception insted
    str[0]="Tej";
    str[1]="Good";
    str[2]="Girl";
    
    String str="SSN"; 
    

    We can get individual character in String:

    char chr=str.charAt(0);`//output will be S`
    

    If I want to to get individual character Ascii value like this:

    System.out.println((int)chr); //output:83
    

    Now i want to convert Ascii value into Charecter/Symbol.

    int n=(int)chr;
    System.out.println((char)n);//output:S
    
    0 讨论(0)
  • 2020-12-22 19:11
    String[] errorSoon = new String[n];
    

    With n being how many strings it needs to hold.

    You can do that in the declaration, or do it without the String[] later on, so long as it's before you try use them.

    0 讨论(0)
  • 2020-12-22 19:13

    You need to initialize errorSoon, as indicated by the error message, you have only declared it.

    String[] errorSoon;                   // <--declared statement
    String[] errorSoon = new String[100]; // <--initialized statement
    

    You need to initialize the array so it can allocate the correct memory storage for the String elements before you can start setting the index.

    If you only declare the array (as you did) there is no memory allocated for the String elements, but only a reference handle to errorSoon, and will throw an error when you try to initialize a variable at any index.

    As a side note, you could also initialize the String array inside braces, { } as so,

    String[] errorSoon = {"Hello", "World"};
    

    which is equivalent to

    String[] errorSoon = new String[2];
    errorSoon[0] = "Hello";
    errorSoon[1] = "World";
    
    0 讨论(0)
  • 2020-12-22 19:16

    You can use below code to initialize size and set empty value to array of Strings

    String[] row = new String[size];
    Arrays.fill(row, "");
    
    0 讨论(0)
  • 2020-12-22 19:19
    String[] arr = {"foo", "bar"};
    

    If you pass a string array to a method, do:

    myFunc(arr);
    

    or do:

    myFunc(new String[] {"foo", "bar"});
    
    0 讨论(0)
提交回复
热议问题