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?
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?
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);
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();
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()]);
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
StringBuilder strB = new StringBuilder();
for(int i = 0; i < size; i++)
{
strB.append("a");
}
String str = strB.toString();