Results 1 to 3 of 3

Thread: Objects

  1. #1
    hawk-dc is offline Member
    Join Date
    Nov 2013
    Posts
    22
    Rep Power
    0

    Default Objects

    Hello! Can smb explain why is there a new object(Rational x = new Rational(...)) created in the main class inside the for-loop??

    import java.util.Random;
    public class MainClass
    {
    public static void main (String[] args )
    {
    Rational sum = new Rational (0,0);

    Random gen = new Random ();

    for (int i = 1; i <= 10; i++)
    {
    Rational x = new Rational (gen.nextInt (10), gen.nextInt (10)+1);
    System.out.println (x.toString ());
    sum = sum.add(x);

    }

    System.out.println ("sum = " + sum);


    }

    }

  2. #2
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Objects

    Hi. Not sure what you're really asking about, but it appears that new Rational objects are created so that they can be added up to 'sum'...

    Do elaborate on what you really want to know.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,776
    Blog Entries
    7
    Rep Power
    21

    Default Re: Objects

    Numbers are immuatable; probably Rational objects are immuatable too (as they should be); b.t.w. the initial value of 'sum' is suspicious, check the Rational class and ask the author of it for details.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Simulating objects selecting objects
    By Asef in forum New To Java
    Replies: 7
    Last Post: 10-27-2012, 08:05 PM
  2. Create objects. What happens to objects on close
    By rru96 in forum New To Java
    Replies: 1
    Last Post: 10-13-2012, 10:46 AM
  3. Replies: 12
    Last Post: 04-29-2012, 03:55 PM
  4. Replies: 1
    Last Post: 01-22-2009, 05:25 PM

Posting Permissions

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