Java: how to initialize String[]?

后端 未结 11 2178
渐次进展
渐次进展 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 19:22
    String[] string=new String[60];
    System.out.println(string.length);
    

    it is initialization and getting the STRING LENGTH code in very simple way for beginners

    0 讨论(0)
  • 2020-12-22 19:23
    String[] args = new String[]{"firstarg", "secondarg", "thirdarg"};
    
    0 讨论(0)
  • 2020-12-22 19:23

    In Java 8 we can also make use of streams e.g.

    String[] strings = Stream.of("First", "Second", "Third").toArray(String[]::new);
    

    In case we already have a list of strings (stringList) then we can collect into string array as:

    String[] strings = stringList.stream().toArray(String[]::new);
    
    0 讨论(0)
  • 2020-12-22 19:23

    You can always write it like this

    String[] errorSoon = {"Hello","World"};
    
    For (int x=0;x<errorSoon.length;x++) // in this way u create a for     loop that would like display the elements which are inside the array     errorSoon.oh errorSoon.length is the same as errorSoon<2 
    
    {
       System.out.println(" "+errorSoon[x]); // this will output those two     words, at the top hello and world at the bottom of hello.  
    }
    
    0 讨论(0)
  • 2020-12-22 19:26

    I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).

    public class StringTest {
        public static void main(String[] args) {
            String[] errorSoon = new String[100];
            errorSoon[0] = "Error, why?";
            //another approach would be direct initialization
            String[] errorsoon = {"Error , why?"};   
        }
    }
    
    0 讨论(0)
提交回复
热议问题