Issue
I would like to to understand how the output works here from this java code.. kindly help ! I took this code from a book called Head First Java here is the code:
public class EchoTestDrive {
public static void main(String[] args) {
Echo e1 = new Echo();
Echo e2 = new Echo(); // the correct answer
//or
Echo e2 = e1; // is the bonus answer!
int x = 0;
while (x < 4) {
e1.hello();
e1.count = e1.count + 1;
if (x == 3) {
e2.count = e2.count + 1;
}
if (x > 0) {
e2.count = e2.count + e1.count;
}
x = x + 1;
}
System.out.println(e2.count);
}
}
class Echo {
int count = 0;
void hello() {
System.out.println("helloooo... ");
}
}
and this is the output:
%java EchoTestDrive
helloooo...
helloooo...
helloooo...
helloooo...
10
Solution
Well....
helloooo...
being output 4 times is from...
while (x < 4) {
e1.hello();
x = x + 1;
}
As for the count to 10, (assuming Echo e2 = e1;
is meant to be Echo e3 = e1;
...
After iteration x = 0
: e1.count == 1, e2.count == 0;
After iteration x = 1
: e1.count == 2, e2.count == 2;
After iteration x = 2
: e1.count == 3, e2.count == 5;
After iteration x = 3
: e1.count == 4, e2.count == 10;
Though that interpretation leaves e3 completely unused.
Answered By - Mike
Answer Checked By - Willingham (JavaFixing Volunteer)