1

How can I initialize a String with dynamic length in Java?

For example, I want to have a String consisting of n characters a, where n is a variable. Can I do that?

Jean-François Corbett
  • 36,032
  • 27
  • 135
  • 183
  • 4
    Ummmm say again?: http://stackoverflow.com/questions/15039519/how-to-dynamically-add-elements-to-string-array – Hanky Panky Jan 17 '14 at 07:28

6 Answers6

5

You can use StringBuilder and define a method called e.g. getString.

public static String getString(char ch, int n){ 
        StringBuilder sb = new StringBuilder(n);
        for (int i=0; i<n; i++){
           sb.append(ch);
        }
        String s = sb.toString();
        return s;
}

Now you can make some calls to this method.

String sA1 = getString('a', 10);
String sA2 = getString('a', 20);
String sB = getString('b', 30);
String sC = getString('c', 5);  
peter.petrov
  • 36,377
  • 12
  • 75
  • 137
2

You can use StringBuilder

StringBuilder sb = new StringBuilder();
String myChar = "a";
int n = 10;
for(int i=0; i<n;i++){
   sb.append(myChar);
}

String myResult = sb.toString();
Abubakkar
  • 15,090
  • 6
  • 52
  • 80
1

Arrays have a fixed length in Java. If you want the size to be dynamic, you need to use a List object

List<String> stringList = new ArrayList<String>();

Have a look at the ArrayList documentation.

And if you need array then

String[] stringArray = stringList .toArray(new String[stringList .size()]);
Reuben
  • 5,406
  • 9
  • 41
  • 54
0

String is immutable. When you are initializing a string it is once. you cant change its size time to time. the size should n`t be dynamic.

Use other option like StringBuilder to do this

User123456
  • 2,299
  • 3
  • 29
  • 41
0
StringBuilder strB = new StringBuilder();
for(int i = 0; i < size; i++)
{
  strB.append("a");
}

String str = strB.toString();
Qadir Hussain
  • 1,258
  • 1
  • 9
  • 25
0

You can use List

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.
rachana
  • 3,258
  • 7
  • 28
  • 48