0

this is my code, from the book Head First Java ...

class Echo {
    int count=0;

    void hello() {
        System.out.println("Helloooo.....");
    }
}

public class EchoTestDrive {
    public static void main(String[] args)  {
        Echo e1 = new Echo();
        Echo e2 = new Echo(); // output 10
        //Echo e2 = e1; // output 24
        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++;
        }
        System.out.println(e2.count);
    }
}

my output:

with the line Echo e2 = e1;
Helloooo.....
Helloooo.....
Helloooo.....
Helloooo.....
24

whereas Echo e2 = new Echo(); gives
Helloooo.....
Helloooo.....
Helloooo.....
Helloooo.....
10

i couldn't understand why that one line affects the output like this, and also, i'v just started learning java, so didnt know what to google either.. so posted it here. hopefully im not being too much of a pest..

thanks in advace for any help.. :)
somjit.

Edited by somjit{}

2
Contributors
2
Replies
7
Views
4 Years
Discussion Span
Last Post by somjit{}
1

Hello Somjit, when you use Echo e1 = new Echo(); Echo e2 = new Echo();
then both the object has separate variable "count" but when you use Echo e2 = e1;
then both of them share "count".Operations on count are performed accordingly and thus you get different results.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.