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 13 of 13

Thread: toString() method

  1. #1
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default toString() method

       public class Operations {  
     
        private int number;  
     
        public Operations(int num) {  
     
            setTheNumber(num);  
        }  
     
        private void setTheNumber(int number) {  
     
            this.number = number;  
        }  
     
        public int getNumber() {  
     
            return number;  
        }  
     
        public Operations add(Operations op) {  
     
            int num1,  
                num2;  
     
            num1 = this.getNumber(); // refers to the receiving objects data members  
            num2 = op.getNumber();   // refers to the argument object  
     
            Operations sum = new Operations(num1 + num2);  
     
            return sum;  
        }  
     
        public Operations subtract(Operations op) {  
     
            int num1,  
                num2;  
     
            num1 = this.getNumber();  
            num2 = op.getNumber();  
     
            Operations difference = new Operations(num1 - num2);  
     
            return difference;  
        }  
     
        // when i add this method  
        public String toString() {  
     
            return getNumber() + "" ;  
        }  
     
        public Operations divide(Operations op) {  
     
            int num1,  
                num2;  
     
            num1 = this.getNumber();  
            num2 = op.getNumber();  
     
            if (num1 == 0 || num2 == 0) {  
     
                System.err.print("Cannot Divide By Zero");  
                System.exit(1);  
            }  
     
            Operations quotient = new Operations(num1 / num2);  
     
            return quotient;  
        }  
     
        public Operations multiply(Operations op) {  
     
            int num1,  
                num2;  
     
            num1 = this.getNumber();  
            num2 = op.getNumber();  
     
            Operations product = new Operations(num1 * num2);  
     
            return product;  
        }  
     
        // Main  
        public static void main(String[] args) {  
     
            Operations num1,  
                       num2;  
     
            Operations sum,  
                       diff,  
                       quot,  
                       prod;  
     
            num1 = new Operations(10);  
            num2 = new Operations(5);  
     
            sum = num1.add(num2);  
            diff = num1.subtract(num2);  
            quot = num1.divide(num2);  
            prod = num1.multiply(num2);  
     
            System.out.println(sum);  
            System.out.println(diff);  
            System.out.println(quot);  
            System.out.println(prod);  
        }  
    }

    when im not yet Overriding the toString() method the output is
    this:

      xxTestxx.Operations@3e25a5  
    xxTestxx.Operations@19821f  
    xxTestxx.Operations@addbf1  
    xxTestxx.Operations@42e816

    but when i include the toString() method
    the output became fine:
      15  
    5  
    2  
    50

    as you can see in my program, i didnt use the method toString().
    but i dont really understand how does it affects the correct string representation,


    i know a bit about memory address representation, so i know the first error,
    thats the only thing i want to understand , why and how does the toString() method affects the output? when im not using it...


    i know this program can be done in a primitive or rather natural way, but im currently reading a chapter about returning objects, this kind of object orientation suits for a fraction program( reducing fration) ,
    i made an example like this so the concern can be noticeable (the fraction program is a bit confusing),


    FOLLOW UP QUESTION:
    question no 2:

    the book says, when you return an object, you are actually returning a REFERENCE,
    now my question is this.

    take a look at this part
    sum = num1.add(num2);

    the object sum is receiving a reference from a returned object from the .add() method,
    now what is the REFERENCE?

    a). Is it the address?
    b) Is it the value (15) - is the value 15 the reference?
    Last edited by chronoz13; January 10th, 2010 at 12:49 AM.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: toString() method

    why and how does the toString() method affects the output? when im not using it...
    If an object does not override the toString method, then the parent class toString method will be called. In this case, that would be the toString ()of the class Object, which in the API specifies:

    The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

    getClass().getName() + '@' + Integer.toHexString(hashCode())

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

    chronoz13 (January 12th, 2010)

  4. #3
    Junior Member
    Join Date
    Jan 2010
    Posts
    3
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: toString() method

    The toString() method is customizable by you. If you create a class, you should include a toString() method. It returns a String, and in the method, you customize what you want the string to be. For example, you could say
    return sum;
    or
    return num1.add(num2);
    Then, when you create an object of that class and want to print out variables of the object, you can call toString(). For example, say you have a circle class and want to print all the variables of the circle at one point -- radius, area, centerX, and centerY. In your class, you could put the method
    public String toString(){
    return "Radius: "+radius+"\nArea: "+area+"\ncenterX: "+centerX+"\ncenterY"+centerY;
    Then, in the main program, you can say:
    Circle myCircle = new Circle(); //Create the Circle object
     System.out.println(myCircle);
    The compiler will call the toString() method to print the object. If the toString() method is not specified by the programmer, the program will print the memory location of the object.

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

    chronoz13 (January 12th, 2010)

  6. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: toString() method

    References aren't too difficult to explain. Think of your variable as a good hunting dog. He will always "point" to the target. He isn't the target (say, a fox), which is very important. If something happens to that fox, say it climbs up a tree or gets shot, the dog will still point to it. The consequences of such are this: any changes you make to that object are independent of the variable reference. So, you can do things like this:

    public void sort(int[] nums)
    {
         // a simple sort algorithm
         for (int i = 0; i < nums.length; i++)
         {
              for (int j = i; j < nums.length; j++)
              {
                   if (nums[j] < nums[i])
                   {
                        int temp = nums[i];
                        nums[i] = nums[j];
                        nums[j] = nums[i];
                   }
              }
         }
    }
     
    public void main(String[] args)
    {
         int[] numbers = {1,2,4,3,5};
         sort(numbers);
         System.out.println("The variable pointed to by numbers got changed without assigning something back the the variable!");
         System.out.println("It now contains: ");
         for (int i = 0; i < numbers.length; i++)
         {
              System.out.println(numbers[i]);
         }
    }

    Notice how I never assigned anything back to the variable numbers, but the object it's pointing to still changed. However, if I happen to do all those operations on a different object, nothing would happen to that original object.

    public void sort(int[] nums)
    {
         int[] sorted = new int[nums.size];
         // copy over values
         for (int i = 0; i < nums.length; i++)
         {
              sorted[i] = nums[i];
         }
         // a simple sort algorithm
         for (int i = 0; i < sorted.length; i++)
         {
              for (int j = i; j < sorted.length; j++)
              {
                   if (sorted[j] < sorted[i])
                   {
                        int temp = sorted[i];
                        sorted[i] = sorted[j];
                        sorted[j] = sorted[i];
                   }
              }
         }
    }
     
    public void main(String[] args)
    {
         int[] numbers = {1,2,4,3,5};
         sort(numbers);
         System.out.println("The variable pointed to by numbers didn't change!");
         System.out.println("It contains: ");
         for (int i = 0; i < numbers.length; i++)
         {
              System.out.println(numbers[i]);
         }
    }

    Referencing and pointing in programming is for the most part synonymous, but there are a few things you may have to worry about the vocabulary in other languages (Java doesn't have any of these differences).
    Last edited by helloworld922; January 12th, 2010 at 12:24 AM.

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

    chronoz13 (January 12th, 2010)

  8. #5
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: toString() method

    thanks for the reply! and I'm glad all things were back into normal again ^^, anyway its still a bit peculiar to me how to understand objects and when and how to use a primitive type and a reference type,(a fraction class for example) darn! because im only studying all by myself.... sorry to ask to much... i didnt learn most of these from school,.. so tnx for the responses... i still have questions to follow regarding this topic.. ill just leave it here for a while

  9. #6
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: toString() method

    oh by the way, another follow up question about objects... while i was reading a section of the book, discussing about parameters and arguments, i notice something about "swapping",

    of course when you pass an argument to a matching parameter, even the values of the parameter will change, it wont affect the argument that has been passed to it..

    my question is, is there any way in java that can swap the values in just one call of a method?
    because when i was taking my C++/C subjects, we were discussing about pointers,
    and we have used pointers in a basic algorithm of swapping... i know that there are no reserved word or any objects in java that can access arbitrary locations such as memory addresess(pointers in other words), but i just want to ask if theres anyway that i can do that "swapping" that we have done in C/C++ in java.?

    ill give an example:

    pulblic static void main(String[] args) {
     
      int num1 = 1,
           num2 = 2;
     
       // after a method call from another classs
       //  num1 = 2;
       //  num2 = 1;
    }

    is this possible in java?

  10. #7
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: toString() method

    and how about this one... is this a good way of swapping a number?

    public class SwapANumber {
     
        private int number;
     
        /**
         * 
         * @param number 
         */
        public void setNumber(int number) {
     
            this.number = number;
        }
     
        /**
         *
         * @return the assigned number
         */
        public int getNumber() {
     
            return number;
        }
     
        /**
         *
         * @return a string representation of this object
         */
        @Override
        public String toString() {
     
            return getNumber() + "";
        }
     
        /**
         * Swaps the objects number
         * 
         * @param num1 the first object to swap
         *
         * @param num2 the second object to swap
         */
        public void swap(SwapANumber num1, SwapANumber num2) {
     
            SwapANumber temp = new SwapANumber();
     
            temp.setNumber(num1.getNumber());
     
            num1.setNumber(num2.getNumber());
            num2.setNumber(temp.getNumber());
        }
     
        public static void main(String[] args) {
     
            SwapANumber number1 = new SwapANumber();
            SwapANumber number2 = new SwapANumber();
     
            SwapANumber swap = new SwapANumber(); // swapping object
     
            number1.setNumber(10);
            number2.setNumber(20);
     
            System.out.println("Before Swapping num1 Is: " + number1);
            System.out.println("Before Swapping num2 Is: " + number2);
     
            swap.swap(number1, number2); // swap the values
     
            System.out.print("\n");
            System.out.println("After Swapping num1 Is: " + number1);
            System.out.println("After Swapping num2 Is: " + number2);
        }
    }

  11. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: toString() method

    First case is impossible in Java because they are primitive types, and primitive types can only be accessed via value, not reference/pointing. Even doing something like this wouldn't change the value:
    public static void main(String[] args)
    {
         int a = 0;
         changeA(a);
         System.out.println("a hasn't changed: " + a);
    }
     
    public static void changeA(int a)
    {
         a = 5;
    }

    The second one is a way to swap a because it is encapsulated in a mutable object, which is passed by reference. This and directly assigning the variable to a return value are the only two ways in Java that you can change the value of a variable.

  12. The Following User Says Thank You to helloworld922 For This Useful Post:

    chronoz13 (January 14th, 2010)

  13. #9
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: toString() method

    hmm another clarification regarding with my first post... the toString() method...

    this is how i understand.. how the toString() method works without even calling it directly by an object....


    no matter what kind of return i will do ..
    for example

     
    public MyClass returnObject() {
     
      return objectOne;
    }
     
    public MyClass returnAnotherObject() {
     
      return objectTwo();
    }
     
    public MyClass returnSomeObject() {
     
      return objectThree()'
    }
     
    public String toString() {
     
      return "Wow you returned an object!";
    }

    so all of the string representation of the object will DEPEND on how i OVERRIDED the toString() method...

    so if I dont oeverride it .. it will look for the default implementation of the toString() method of the object class..

    in this case... i have 3 methods that returns an object(reference rather) and if i pass those returned reference in the .println() method.. it will display the returned value of the toString() method that i overrided... ahha ...

    Wow you returned an object!

    tnx for helping me clearing this out...
    so im thinking that this is a better way to organize my class and objects... by passing and returning of objects instead of just returning a primitive types.....

  14. #10
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: toString() method

    Yeah the toString method is a nice one, the actual hashCode that is used in the default toString method on the Object class is actually the native object handle so its going to be a unique hashCode for each object.

    You could of course override the hashCode method as well

    // Json

  15. The Following User Says Thank You to Json For This Useful Post:

    chronoz13 (January 16th, 2010)

  16. #11
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: toString() method

    frankly speaking , i dont have any idea what is hashcode for now...

  17. #12
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: toString() method

    Hashing is a technique to transfer any object into an "index" that can be used to retrieve that specific object from a hash table. hashcode() just happens to be Java's method for creating a hash of an object. The hash function can pretty much be anything you want (provided it always gives the same hash code back if run on the same object), and is used in making efficient data addition/removal, and also for cryptography. It's best to have a semi-random distribution of objects for either case because that's what gives the hash table efficiency and encryption hard to crack.

  18. The Following User Says Thank You to helloworld922 For This Useful Post:

    chronoz13 (January 18th, 2010)

  19. #13
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: toString() method

    The better the hashcode the faster it is to find the right object in for instance a HashMap.

    Helloworld will like this one.

    Think of it like buckets. When you use a HashMap and you do get(object) it checks the hashCode of object and tries to find the bucket for that hashCode. If it finds that bucket it will look through it to find the correct object using the objects equals method.

    Now the problem is if all your objects have a hashCode of "1" the map will have to compare every single object to find the correct one but if you use the hashCode somewhat clever it will be a lot easier to find the right object.

    Anyways, over course this is I believe, but how can you not love buckets

    // Json

  20. The Following User Says Thank You to Json For This Useful Post:

    chronoz13 (January 19th, 2010)

Similar Threads

  1. ClassCastException in Double Linked List toString
    By Rastabot in forum Collections and Generics
    Replies: 2
    Last Post: April 24th, 2009, 11:48 AM