suppose I am getting 2 strings
"About product" and "About Us"
and I want to store them in String array like
myArray[]={"About product", "About Us"};
how to do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You are reading strings dynamically, and you want to end up with an array of them (
String[]), but you don’t know how many there are until you’ve read them all.In Java, arrays are of fixed length, so the answer is not to store them in an array until you know how many there are. What you need is a temporary list. There are several lists you can use, depending upon certain performance characteristics, but the
ArrayListis a reasonable choice.will create a new array list. Then in a loop you can read a string and add it to the list (which will expand to accommodate each new entry):
and then you can create and fill the array you really wanted. There is a convenience method on
Lists for doing this, like this:It is not obvious at first glance why the
toArraymethod needs to have the array passed to it, but it makes the call typesafe, and you don’t have to cast the result toString[]. You can read the JavaDoc for this method here.