CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 2016
    Posts
    2

    Question Help on understanding the following basic java code

    Hi all,

    I just started learning Java and I don't understand the output for this particular code and hoping someone could shed some light for me:

    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();

    e1.count = e1.count + 1;
    e2 = e1;

    int x = 0;

    while ( x < 4 ) {
    e1.hello();

    if ( x < 4) {
    e2.count = e2.count + 1;
    }
    if ( x == 3) {
    e2.count = e2.count + e1.count;
    }
    x = x + 1;
    }
    System.out.println(e2.count);
    }
    }


    The output is:

    helloooo...
    helloooo...
    helloooo...
    helloooo...
    10


    But I don't understand how the number is 10 and not 6. From what I read I got the following output:

    e1.count = 1
    elloooo, helloooo,helloooo,helloooo
    e2.count = 5
    x = 4

    Apologies for such a noobie question but any answer is greatly appreciated.

    Thanks in advance

  2. #2
    Join Date
    Jun 1999
    Location
    Eastern Florida
    Posts
    3,875

    Re: Help on understanding the following basic java code

    Code:
      e2 = e1; // now e2 and e1 point to the same object
    The original instance pointed to by e2 is lost.
    To make the code clearer, replace all e2 with e1 following the above assignment statement.
    Norm

  3. #3
    Join Date
    Sep 2016
    Posts
    2

    Re: Help on understanding the following basic java code

    Quote Originally Posted by Norm View Post
    Code:
      e2 = e1; // now e2 and e1 point to the same object
    The original instance pointed to by e2 is lost.
    To make the code clearer, replace all e2 with e1 following the above assignment statement.
    Thanks, makes more sense

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured