Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Affecting Point objects with methods - a beginner's failed attempt

  1. #1
    Junior Member
    Join Date
    Jun 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Affecting Point objects with methods - a beginner's failed attempt

    I am brand new to Java (well, programming in general) and learning on my own using Building Java Programs (Reges/Stepp).

    An exercise in ch. 3 supplies some code to define two points, send them to a method that trades their (x,y) values, then prints these values. I'm wondering why my method had no effect.

     
    public static void number10() {
    // Here is the code supplied by the textbook.
    		Point p1 = new Point(5, 2);
    		Point p2 = new Point(-3, 6);
     
    		swapPoints(p1, p2);
     
    		System.out.println("(" + p1.x + "," + p1.y + ")");
    		System.out.println("(" + p2.x + "," + p2.y + ")");
    	}
     
    	// Here is the method I created, which seemingly has no effect
    	public static void swapPoints(Point new1, Point new2) {
    		Point dummy = new Point(0, 0);
    		dummy = new1;
    		new1 = new2;
    		new2 = dummy;
    	}

    The desired output is:

    (-3, 6)
    (5, 2)

    When I ran it, the output was:

    (5, 2)
    (-3, 6)

    I thought swapping new1 and new2 in my method would swap the objects referenced by p1 and p2, but apparently not.

    Initially I wrote the method to return new1 and new2 after swapping their values, but concluded that it's either not possible to return two values, or I don't know how to do it yet.

    I'd appreciate a helpful word about why my method did not swap the actual objects, and what would be a better method to do so. Thank you in advance.


  2. #2
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    609
    My Mood
    Sleepy
    Thanks
    10
    Thanked 93 Times in 86 Posts

    Default Re: Affecting Point objects with methods - a beginner's failed attempt

    Java is call by value. Actually you're passing copies of the references to your Points into the swap methods. You're altering the copies and the original references remain unchanged.
    To actually swap you have to reset the x and y values in the swap method.

  3. The Following User Says Thank You to PhHein For This Useful Post:

    THE ULTIMATE CYBER MACHIN (July 17th, 2013)

  4. #3
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Affecting Point objects with methods - a beginner's failed attempt

    The x/y values of a Point are called the state of the point object.

    As mentioned Java is pass by value. This has to do with variables and their values (not objects and their state). The bottom line of pass by value is that if you use variables in a method call, those variables will always have the same values after the method call as they did before it. The values being references to objects.

    The method can change the state of the points referenced by the values it is passed: first by swapping the x-values, then repeating that for the y-values.

  5. The Following User Says Thank You to pbrockway2 For This Useful Post:

    THE ULTIMATE CYBER MACHIN (July 17th, 2013)

  6. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Affecting Point objects with methods - a beginner's failed attempt

    All of the words given you so far are great, but I'm not sure you can see the answer to your question in them. The code below is modified to demonstrate how one method (your original, renamed) operates on copies of the original variables, while the second method I wrote operates on the original variables, producing the desired results. Let me know if you have any questions or are still not clear about what's going on.
    import java.awt.Point;
     
    public class TestClass
    {
        // notice the declaration of p1 and p2 has to be moved outside the main()
        // method to be 'visible' (in the scope of) the method swapOriginalPoints()
        static Point p1;
        static Point p2;
     
        public static void main (String args[])
        {
            number10();
        }
     
        public static void number10()
        {
            // Here is the code supplied by the textbook.
            p1 = new Point(5, 2);
            p2 = new Point(-3, 6);
     
            // GB: this call passes the original points to the method which then
            // creates copies of the points and acts on the copies, not the originals
            swapPointCopies(p1, p2);
     
            System.out.println("(" + p1.x + "," + p1.y + ")");
            System.out.println("(" + p2.x + "," + p2.y + ")");
     
            // GB: this call passes nothing to the method. the method can access the
            // original p1 and p2 variables directly for a lot of reasons that i
            // hope become obvious as you study the differences
            swapOriginalPoints();
     
            System.out.println("(" + p1.x + "," + p1.y + ")");
            System.out.println("(" + p2.x + "," + p2.y + ")");
        }
     
        // Here is the method I created, which seemingly has no effect
        // GB: note that this method creates copies of the variables passed to it
        // AND OPERATES ON THE COPIES, not the original variables
        public static void swapPointCopies( Point new1, Point new2 )
        {
            Point dummy = new Point(0, 0);
            dummy = new1;
            new1 = new2;
            new2 = dummy;
        }
     
        // GB: here is another method that operates on the original variables
        // rather than copies
        public static void swapOriginalPoints()
        {
            Point dummy = new Point(0, 0);
            dummy = p1;
            p1 = p2;
            p2 = dummy;
        }
     
    }

  7. The Following User Says Thank You to GregBrannon For This Useful Post:

    thatolkevin (June 22nd, 2013)

  8. #5
    Junior Member
    Join Date
    Jun 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Affecting Point objects with methods - a beginner's failed attempt

    Thank you all for your comments. My understanding from the chapter of the textbook was that objects differed from..static elements (?) in that any variables that pointed to them could change the value of the object (and thus the value of all variables making reference to them). I do understand better, thanks to your comments, about when the object is changed and when only copies are affected.

    I'll take it as an encouraging sign that no one has apparently seen an easy answer to the direct question in the textbook, i.e. passing original points into a method and having them changed thereby (unless I've missed something). GB's example looks like a good way to acquire the desired swap, but not without modification to the code supplied by the textbook (in that it doesn't pass the points to the method that works, as the textbook calls for).

    I'll file this away and come back to it someday when I've learned significantly more. Thanks again for your time in considering the problem.

  9. #6
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Affecting Point objects with methods - a beginner's failed attempt

    I'll take it as an encouraging sign that no one has apparently seen an easy answer to the direct question in the textbook, i.e. passing original points into a method and having them changed thereby (unless I've missed something).
    Both PhHein and myself did address just this I think.

    The question was given here as "An exercise in ch. 3 supplies some code to define two points, send them to a method that trades their (x,y) values, then prints these values." Hopefully you can see now that your method merely does something to the values of a couple of variables (new1 and new2) that only exist within the method and have no effect at all on the values of other variables (specifically, p1 and p2).

    Moreover the question did not ask you to trade the values of p1 and p2: what it asked you to do was to trade the x- and y-values of the points referenced by those variables.

    What PhHein suggested was that "To actually swap you have to reset the x and y values in the swap method". I suggest you keep p1 and p2 as local variables of the main() method just as the question had them. And implement swapPoints() to do what was suggested: namely, swap the argument points' x-values and then swap their y-values.

  10. #7
    Junior Member
    Join Date
    Jun 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Affecting Point objects with methods - a beginner's failed attempt

    Quote Originally Posted by pbrockway2 View Post
    Moreover the question did not ask you to trade the values of p1 and p2: what it asked you to do was to trade the x- and y-values of the points referenced by those variables.

    What PhHein suggested was that "To actually swap you have to reset the x and y values in the swap method". I suggest you keep p1 and p2 as local variables of the main() method just as the question had them. And implement swapPoints() to do what was suggested: namely, swap the argument points' x-values and then swap their y-values.
    I have been looking over and considering for days what has been written here and the original textbook problem, and while I believe I understand all the aforementioned comments, I still am not grasping how to apply the suggestions.

    If the best approach is to swap the argument points' x-values and then their y-values, then is it not necessary to return two values from the swapPoint method (in order to be faithful to the original textbook code)? As I understand, only one value can be returned or there is a compiler error.

    And I'm at a loss to see how the x- and y-values of the original p1 and p2 can be modified at all by a method that cannot see them, but can only work with copies.

    Pardon my thickness, and thanks again in advance for help with this.

  11. #8
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Affecting Point objects with methods - a beginner's failed attempt

    There's no problem with returning two things. The method is void, so it returns nothing at all!

    Understand that throughout this program you have two points. Just two. And that never changes.

    But you have a number of variables that refer to those points. In main() p1 and p2 refer to the two points. Later, in the swapPoints() method, new1 and new2 refer to those same two points. It is true that new1 and new2 get their values as copies of the values of p1 and p2, but those values are references.

    The reference values are copied. The points are not copied.

    I'm at a loss to see how the x- and y-values of the original p1 and p2 can be modified at all by a method that cannot see them
    The x- and y-values of the points referenced by p1 and p2 *can* be seen by the swapPoints() method. It uses the local new1 and new2 variables to see them. What main() calls p1.x is exactly the same thing as what swapPoints() calls new1.x. Change one and you change the "other".

    is it not necessary to return two values from the swapPoint method (in order to be faithful to the original textbook code)?
    No, the original textbook code declared swapPoints() as a void method. Nothing is returned.

    Rather, swapPoints() uses new1 and new2 to swap the points' x- and y-values. And after it is called main() "sees" the swapped values using its own variables (references) p1 and p2.

  12. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Affecting Point objects with methods - a beginner's failed attempt

    Perhaps this article will help.

    And if you want to read even more, try this one.

  13. #10
    Junior Member
    Join Date
    Jun 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Affecting Point objects with methods - a beginner's failed attempt

    Back at it after a hiatus, and I finally had my "Eureka!" moment. Seems so simple now after the fact. Thanks, everyone, for the helpful suggestions.

    // Method for problem 10
    	public static void swapPoints(Point new1, Point new2) {
    		int dummy = new1.x;
    		new1.x = new2.x;
    		new2.x = dummy;
    		dummy = new1.y;
    		new1.y = new2.y;
    		new2.y = dummy;
    	}


  14. #11
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    609
    My Mood
    Sleepy
    Thanks
    10
    Thanked 93 Times in 86 Posts

    Default Re: Affecting Point objects with methods - a beginner's failed attempt

    Well done

Similar Threads

  1. Problem with calling objects from same-class methods in main
    By thekbon in forum Object Oriented Programming
    Replies: 12
    Last Post: December 18th, 2012, 01:10 AM
  2. Replies: 17
    Last Post: July 27th, 2012, 12:52 AM
  3. Brand New/First Attempt
    By kevinco in forum What's Wrong With My Code?
    Replies: 3
    Last Post: August 14th, 2011, 08:45 PM
  4. [SOLVED] Word Scramble Using Objects & Methods
    By Whitechapel in forum Object Oriented Programming
    Replies: 3
    Last Post: May 23rd, 2010, 12:38 PM
  5. [SOLVED] Java Beginner: Help with methods and returning values (hailstone program)
    By alf in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 14th, 2010, 06:28 PM