Home » Java » java – How many results in these two programs and why? – Stack Overflow

java – How many results in these two programs and why? – Stack Overflow

Posted by: admin February 20, 2020 Leave a comment

Questions:
//Number 1
    int x = 2;
    while (x < 200) {
        System.out.println(x + " ");
        x *= x;

Output: 3

//Number 2
    String word = "a";
    while (word.length() < 10) {
        word = "b" + word + "b";
    }

    System.out.println(word);

Output: bbbbbabbbbb

Number 1: Why is the output 3? I’m doing 2*2*2*2*2*2*2 = 128. Therefore, I think the answer should be 7?

Number 2: What happened there? And is the result “zero” or “infinity” or “unknown” or a number? Why?

Answers:

For Number#1 you are not multiplying by a factor of 2 but instead you are mutiplying x by the power of x

iteration #0 - x = 2
iteration #1 - x = 4
iteration #2 - x = 16
iteration #3 - x = 256

change x *= x; to x *= 2;

For Number#2 just use a debugger to see what you are actually doing:

iteration #1 - word = "bab";
iteration #2 - word = "bbabb";
iteration #3 - word = "bbbabbb";
iteration #4 - word = "bbbbabbbb";
iteration #5 - word = "bbbbbabbbbb"; 

word‘s length now is greater than 10, so it stops