I am a newbie to Java. I wrote the following program and got the output below.
OUTPUT:
1
a out=
x=0 1 test..
x=1 1 gotcha..
If strings are immutable, how come I can apparently change the value of "thisCycle" from "0" to "1" and it prints out the new string value? Why do I get 2 lines of output in the "for" loop? Why does the first string have 2 periods appended to it?
Thanks
import java.util.ArrayList;
public class Main {
/**
* @param args
*/
private static final ArrayList<String> ListContents=new ArrayList<String>();
public static void main(String[] args) {
// TODO Auto-generated method stub
String thisCycle="Cycle";
thisCycle="0";
// advance to next cycle
if (thisCycle.equals("0")) thisCycle="1";
System.out.println(thisCycle);
//
String a1="test";
String a2="gotcha";
ListContents.add(a1);
ListContents.add(a2);
StringBuilder a_out=new StringBuilder("");
System.out.println("a out="+a_out);
for(int x=0;ListContents.size()>x;x++) {
a_out.delete(0, a_out.length()+1);
if (thisCycle.equals("0")) a_out.append(ListContents.get(x)).append(". ");
if (thisCycle.equals("1")) a_out.append(ListContents.get(x)).append(".. ");
System.out.println("x="+x+" "+thisCycle+" "+a_out);
}
}
}