First approach would be to use String.concat() as below,
String str="";
String id ="";
for(int i=0;i<=5;i++){
id = driver.findElement(By.xpath("//[@id='selectpatientid_"+i+"']")).getText();
str.concat(id);
}
System.out.println(str);
But the above approach causes multiple String creations.
I suggest to go for StringBuilder,
StringBuilder finalStringb =new StringBuilder();
String id ="";
for(int i=0;i<=5;i++){
id = driver.findElement(By.xpath("//[@id='selectpatientid_"+i+"']")).getText();
finalStringb.append(id);
}
System.out.println(finalStringb);
Note--`The concat() method of String class takes the string as parameter, it appends the specified string, and returns a new String.
Actually,this concat() method creates a new char array for both strings, and then put both strings into the new array, and then again creates a new String with that array.Its degrade the performance.
StringBuilder works more efficent. in short if you are useing String concatenation in a loop then you can go with StringBuilder (not StringBuffer) instead of a String, because it is much faster and consumes less memory.