Overiding the toString method

If I have a method which takes an array of strings as the first argument and a string as the second argument.
I will compare the string to each index in the passed in array and add the smaller strings to an arraylist.
firstly to return an ArrayList, what type of method would it be, String?
Then how is the toString method overridden to print out the ArrayList if the ArrayList could vary depending on the passed in arguments?
;)

Encephalopathic wrote:
Implode wrote:
If I want to print out an ArrayList using a for loop, the toString method needs to be overridden?No, not at all. You simply loop through the ArrayList and println each element. Now if the elements are complex objects, then the toString method of the class that the elements are composed of may need a toString override.
I had to do that with previous examples.Code is worth a thousand words. What do you mean here? Did what?
Yeah, sorry, I guess I never explained properly. I know how to override toString method, (totally serperate question)but what if the ArrayList was containing object references , and the ArrayList was built depending on arguments passed to a method , how would the toString be overridden then?Again, you would need to have a toString override of the objects held by the ArrayList, not the ArrayList itself.
For e.g.,
import java.util.ArrayList;
import java.util.Random;
public class MyFoo {
private String text;
private int value;
public MyFoo(String text, int value) {
super();
this.text = text;
this.value = value;
@Override // here's the necessary toString override
public String toString() {
return text + ": " + value;
public static void main(String[] args) {
String[] strings = {"Mon", "Tues", "Wed", "Thurs", "Fri"};
Random random = new Random();
ArrayList<MyFoo> fooList = new ArrayList<MyFoo>();
for (String text : strings) {
fooList.add(new MyFoo(text, random.nextInt(100)));
// to print out in a for loop:
for (MyFoo myFoo : fooList) {
System.out.println(myFoo);
}Edited by: Encephalopathic on Nov 15, 2009 9:11 AMI did override toString using complex objects in previous examples(university assignments).
Thanks for the help. Forget the question. It was sidetrack.
Edited by: Implode on Nov 15, 2009 9:23 AM

Similar Messages

  • Using JOptionPane to exit program & Using toString method

    Hello,
    In my program I have to use a toString method below
    public String toString(Hw1NCBEmployee[] e)
            String returnMe = String.format(getStoreName() + "\n" + getStoreAddress() + "\n" + getCityState() +  "\nYou have " + getEmpCount() + "employee(s)");
            return returnMe;
    }Now, at first, when I initially tested my code, it was working just fine, printing out the right way
    Point is -- now that Im practically finished with my program, and am going back and running it - calling the toString method gives me the address rather than the information . . . Can anyone help me with this issue??
    Also, Im using JOptionPane to display everything, but -- at first, it worked fine, then (around the same time I started having the above problem) it stopped exiting the do-while loop:
    while(go)
                 int option = JOptionPane.showConfirmDialog(null, "Do you want to enter employee information?", "Welcome!", JOptionPane.YES_NO_OPTION);
                     if(option == JOptionPane.NO_OPTION)
                        go = false;  //exit loop
            

    ncjb wrote:
    well, for the toString - I have to print out the info inside the array -- am I right in thinking that the only way to do this is to pass in the array ??If the array is part of the class then there is no need to pass it as a parameter. If it is being passed in from outside the class then I have to question your design. Why should class X being formatting data that is not a representation of itself?
    and i have 2 other files that go with this program . . . I just want to know if there is a way to make sure that when the user presses the NO option, it will exit the loop -- the piece of code you see if apart of an entire method (not long) -- do you want me to include this??You read that link I provided REAL quick!

  • ToString() method in my User defined Exception...How is it getting called ?

    CustomException.java
    public class CustomException extends Exception
         private int age;
         public CustomException(int age)
         this.age = age;
         public String toString()
         return "this is my exception";
    ExceptionTest.java
    public class ExceptionTest
         static int age=-1;
         public static void main(String args[]) throws Exception
              if(age<0)
              throw new CustomException(age);
    After executing ExceptionTest.java , the result is
    Exception in thread "main" this is my exception at ExceptionTest.main(ExceptionTest.java:8)
    I am just throwing CustomException , to my knowledge only the constructor should run ?
    What i see is message "this is my exception" is within the toString() method - which i never called.
    From where is the toString() method getting called ?
    Also ,
    If I want an object of my class to be thrown as an exception object, what should I do?

    Your main method is defined as throwing Exception, so the JVM catches the Exception (since nothing in your code does). And it does the equivalent of e.printStackTrace() which, among other things, outputs the result of toString().

  • How  to override toString() method ?

    class  Test
    String x[];
    int c;
    Test(int size)
    x=new String[size];
    c=-1;
    public void addString(String str)
    x=new String
    x[++c]=str;
    public void String toString()
    //  i want to override toString method to view the strings existing in the x[]...
    //   how do i view the strings ?
    //  probabily i should NOT use println() here (..as it is inside tostring() method ..right? )
    //   so i should  RETURN   x[] as an array...but the  toString() method return  type is String not the String array!.
    //   so i am in trouble.
    so in a simple way my question is how do i override toString() method to view the Strings stored in the array ?
    i am avoiding println() bcoz of bad design.
    }

    AS you said, the toString method returns a String - this String is supposed to be a representation of the current instance of your class's state. In your case, your class's state is a String array, so you just pick a format for that and make a String that fits that format. Maybe you want it to spit out something like:
    Test[1] = "some string"
    Test[2] = "some other String"If so, code something like:public String toString() {
        StringBuffer returnValue = new StringBuffer();
        for (int i = 0; i < x.length; i++) {
            returnValue.append("Test[" + i + "] = \"" + x[i] + "\"";
        return returnValue.toString();
    } If you don't mind the formatting of the toString method that Lists get, you could just do something like:public String toString() {
        return java.util.Arrays.asList(this).toString();
    } and call it good. That will print out something like:
    [Some String, another String, null]Depending on what's in your array.
    Good Luck
    Lee

  • JSP Tags, EL and toString() method

    Hi,
    I want to pass a Java object to a custom tag via EL, but am finding that since the class has a toString() method, EL automatically converts the class to a string using the toString method. Consequently, I get an error because the string cannot be cast back to the parent object in the tag handler class.
    I played around with a dummy class and found that if the toString() method wasn't defined, EL would pass the object as is without converting to a string.
    Is there some reason for this behaviour and is there some way I can get around this without having to remove the toString() method ? The object I am trying to process is from an external library, so I can't modify it.
    Thanks for any tips on this.
    Paul Samuel

    My initial guess was that you hadn't defined the type of the attribute, and it was defaulting to String as a result. Now that I've seen the tld file thats obviously not the cause.
    Next guess: EL evaluation is disabled, and it is interpreting ${model.results} as a string, rather than evaluating it.
    1 - What happens if you just put ${1 + 1} onto a JSP page. Does it print ${1 + 1} or evaluate it as 2?
    2 - What server are you using? What version? Which J2EE spec does it support?
    You can use the following JSP snippet to confirm this info:
    <h2> Server Info</h2>
    Server info = <%= application.getServerInfo() %> <br>
    Servlet engine version = <%=  application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
    Java version = <%= System.getProperty("java.vm.version") %><br>
    Session id = <%= session.getId() %><br>3 - What version is your web.xml declared as? 2.3 or 2.4?
    4- If you have a Servlet2.4/JSP2.0 container (eg Tomcat 5), try putting the following on your page and see if it works
    <%@ page isELIgnored="false" %>
    http://forum.java.sun.com/thread.jspa?threadID=629437&tstart=0
    Cheers,
    evnafets

  • How convert results to toString method

    Hi All,
    I am facing the problem to display the results in out.println in jsp pages like...
    I thing it must convert to toSting is it right...
    kindly give ur valualbe reply how to convert toString

    >>>
    override the toString() method in the class ofthe
    the object returned by getRepCdrOptType() (classof
    the reference repCdrOptType in your FormBean)
    ram.pl. give more details.....What does getRepCdrOptType() return -
    1. String[] ? (which is what it looks like)
    In which case ur code should be like this
    <%
    String[] optType =
    =  reportsSelectTypeForm.getRepCdrOptType();
    for(int i = 0; i< optType.length ; i++){
    %>
    <%=optType%>
    <%}%>
    2. Object of some class ?? then override the
    the toString() method in the class.
    ram.
    Thanks for your valuable reply but i am in starting of java so now i give the 3 files for u. Give the how i print the original value instance of [Ljava.lang.String;@104e28b. And also I have one more problem.That is i have 5 screens. i store the values in session and print the last page. After click finished button the control comes to first page and again goes to that flow. But i am going to second time the previouse values are displayed(like if  we check one check box. it always checked in second time also..... But i try to solve this problem to give null in reset() in form bean. But the session values r deleted when going to the next page. kindly give ur idea.
    Form Bean
    public class ReportsSelectTypeForm extends ValidatorForm {
         // --------------------------------------------------------- Instance Variables
         private Integer id;
         /** Report Select Type Screen Property */
         private String repSelTypeAll;
         private Integer repSelTypeValue;
         private String repSelTypeDesc;
         private String repSelTypeInd;
         /** Report CDR Options Screen Property */
         private String[] repCdrOptType = {"ISDN","IP"};
         private String[] repCdrOptDir = {"Outbound Direction"};
         private String[] repCdrOptStatus={"Success Status"};
         private String[] repCdrOptAvlFields;
         private String[] repCdrOptSelFields;
    /** ----------------------------------------------- Report Select Type Screen ----------------------------------------------- */
          * Returns the id.
          * @return String
         public Integer getId() {
              return id;
          * Set the id.
          * @param id The id to set
         public void setId(Integer id) {
              this.id = id;
          * Returns the repSelTypeAll.
          * @return String
         public String getRepSelTypeAll() {
              return repSelTypeAll;
          * Set the repSelTypeAll.
          * @param repSelTypeAll The repSelTypeAll to set
         public void setRepSelTypeAll(String repSelTypeAll) {
              this.repSelTypeAll = repSelTypeAll;
          * Returns the repSelTypeValue.
          * @return String
         public Integer getRepSelTypeValue() {
              return repSelTypeValue;
          * Set the repSelTypeValue.
          * @param repSelTypeValue The repSelTypeValue to set
         public void setRepSelTypeValue(Integer repSelTypeValue) {
              this.repSelTypeValue = repSelTypeValue;
          * Returns the repSelTypeDesc.
          * @return String
         public String getRepSelTypeDesc() {
              return repSelTypeDesc;
          * Set the repSelTypeDesc.
          * @param repSelTypeDesc The repSelTypeDesc to set
         public void setRepSelTypeDesc(String repSelTypeDesc) {
              this.repSelTypeDesc = repSelTypeDesc;
          * Returns the repSelTypeInd.
          * @return String
         public String getRepSelTypeInd() {
              return repSelTypeInd;
          * Set the repSelTypeInd.
          * @param repSelTypeInd The repSelTypeInd to set
         public void setRepSelTypeInd(String repSelTypeInd) {
              this.repSelTypeInd = repSelTypeInd;
         /** ----------------------------------------------Reports CDR Options Screen  -------------------------------------------*/
          * Returns the repCdrOptType.
          * @return String
         public String[] getRepCdrOptType() {
              return repCdrOptType;
          * Set the repCdrOptType.
          * @param repCdrOptType The repCdrOptType to set
         public void setRepCdrOptType(String[] repCdrOptType) {
              this.repCdrOptType=repCdrOptType;
          * Returns the repCdrOptDir.
          * @return String
         public String[] getRepCdrOptDir() {
              return repCdrOptDir;
          * Set the repCdrOptDir.
          * @param repCdrOptDir The repCdrOptDir to set
         public void setRepCdrOptDir(String[] repCdrOptDir) {
              this.repCdrOptDir=repCdrOptDir;
          * Returns the repCdrOptStatus.
          * @return String
         public String[] getRepCdrOptStatus() {
              return repCdrOptStatus;
          * Set the repCdrOptStatus.
          * @param repCdrOptStatus The repCdrOptStatus to set
         public void setRepCdrOptStatus(String[] repCdrOptStatus) {
              this.repCdrOptStatus=repCdrOptStatus;
          * Returns the repCdrOptAvlFields.
          * @return String
         public String[] getRepCdrOptAvlFields() {
              return repCdrOptAvlFields;
          * Set the repCdrOptAvlFields.
          * @param repCdrOptAvlFields The repCdrOptAvlFields to set
         public void setRepCdrOptAvlFields(String[] repCdrOptAvlFields) {
              this.repCdrOptAvlFields=repCdrOptAvlFields;
          * Returns the repCdrOptSelFields.
          * @return String
         public String[] getRepCdrOptSelFields() {
              return repCdrOptSelFields;
          * Set the repCdrOptSelFields.
          * @param repCdrOptSelFields The repCdrOptSelFields to set
         public void setRepCdrOptSelFields(String[] repCdrOptSelFields) {
              this.repCdrOptSelFields=repCdrOptSelFields;
    Action Class forward the success
    JSP Page
    <%@ page language="java" import="java.util.*, com.polycom.e100.ui.action.reports.*,com.polycom.e100.ui.form.reports.*"%>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
    <%@ page language="java" contentType="text/html" %>
    <jsp:useBean id="clock" class="java.util.Date" />
    <script language="javascript">
         function getsubmitAction(actionValue)
              document.reportsSelectTypeForm.submitAction.value = actionValue;
    </script>
    <html:form action="/action/reports/dumpValues">
    <html:hidden property="submitAction" value=""/>
    <%
         ReportsSelectTypeForm reportsSelectTypeForm = (ReportsSelectTypeForm)session.getAttribute("reportsSelectTypeForm");
    %>
    <table class="form_outer_table">
         <tr>
              <td class="form_header_row">
              <bean:message key="polycom.e100.reports.viewrep.header"/>
              </td>
         </tr>
         <tr>
              <td align="center">
                   <h3><bean:message key="polycom.e100.reports.viewrep.reptype"/></h3>
                   <h5><bean:message key="polycom.e100.reports.viewrep.repname"/></h5>
                   <h5><bean:message key="polycom.e100.reports.viewrep.repdesc"/></h5>
                   <table width="600" border="0">
                        <tr>
                             <td><bean:message key="polycom.e100.reports.viewrep.repstart"/>: <% out.println(reportsSelectTypeForm.getRepSelDateStart());%> </td>
                             <td><bean:message key="polycom.e100.reports.viewrep.repend"/>: <% out.println(reportsSelectTypeForm.getRepSelDateEnd());%></td>
                             <td> </td>
                             <td> </td>
                             <td> </td>
                             <td> </td>
        <td><bean:message key="polycom.e100.reports.viewrep.reptime"/>:<jsp:getProperty name="clock" property="hours" />:<jsp:getProperty name="clock" property="minutes" /> GMT </td>
      </tr>
      <tr>
        <td colspan="7" align="center"><table class="newWizardInner" >
          <tr>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repid"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.reporg"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repdt"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repdur"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repctype"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repdir"/></b></td>
              <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repbw"/></b></td>
          </tr>
          <tr>
            <td><% out.println(reportsSelectTypeForm.getId());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepSelTypeInd());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepSelDateStart());%></td>
            <td> </td>
            <td><% out.println(reportsSelectTypeForm.getRepCdrOptType());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepCdrOptDir());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepSiteOptText());%></td>
          </tr>
             </table></td>
      </tr>
      <tr>
       <td colspan="7"><table class="newBottomTab" >
          <tr><p> </p>
            <td><html:submit property="back" value="<< Back"  style="width:100px" onclick="getsubmitAction('BACK')"/>
              <html:submit property="finished" value="Finished" style="width:100px" onclick="getsubmitAction('NEXT')"/></td>
          </tr>
        </table></td>
        </tr>
    </table>
    <p> </p>
    </td>
    </tr>
    </table>
    </html:form>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Confusion with toString() method

    hi...can you please tell me how to use the toString() method? i'm trying to print out a Vector and convert whatever is in it to strings but the memory addresses keep appearing. i tried using the method to convert (ie. getNames.toString, where getNames returns a vector, but it doesnt seem to work. i dont know what the problem is. i would really appreciate your help...

    The objects in the Vector (or whatever collection
    type you use) need to implement their owntoString()
    method. Otherwise they just inherit
    java.lang.Object's implementation, which gives you
    the result you are seeing -- how should the system
    magically know what to show for a string
    representation of any willy-nilly object?Furthermore: the OP actually needs to call it on the
    Vector's elements, not on the Vector itself.Not necessarily. I believe Vector.toString() iterates over the elements in it, invoking toString() on them.

  • Problem Using toString method from a different class

    Hi,
    I can not get the toString method to work from another class.
    // First Class Separate file MyClass1.java
    public class MyClass1 {
         private long num1;
         private double num2;
       public MyClass1 (long num1, double num2) throws OneException, AnotherException {
            // Some Code Here...
        // Override the toString() method
       public String toString() {
            return "Number 1: " + num1+ " Number 2:" + num2 + ".";
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        public static void main(String[] args) {
            try {
               MyClass1 myobject = new MyClass1(3456789, 150000);
               System.out.println(myobject);
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
    }My problem is with the System.out.println(myobject);
    If I leave it this way it displays. Number 1: 0 Number 2: 0
    If I change the toSting method to accept the parameters like so..
    public String toString(long num1, double num2) {
          return "Number 1: " + num1 + " Number 2:" + num2 + ".";
       }Then the program will print out the name of the class with some garbage after it MyClass1@fabe9. What am I doing wrong?
    The desired output is:
    "Number 1: 3456789 Number 2: 150000."
    Thanks a lot in advance for any advice.

    Well here is the entire code. All that MyClass1 did was check the numbers and then throw an error if one was too high or too low.
    // First Class Separate file MyClass1.java public class MyClass1 {
         private long num1;
         private double num2;
         public MyClass1 (long num1, double num2) throws OneException, AnotherException {              
         // Check num2 to see if it is greater than 200,000
         if (num2 < 10000) {
                throw new OneException("ERROR!:  " +num2 + " is too low!");
         // Check num2 to see if it is greater than 200,000
         if (num2 > 200000) {
                throw new AnotherException ("ERROR!:  " +num2 + " is too high!");
         // Override the toString() method
         public String toString() {
              return "Number 1: " + num1+ " Number 2:" + num2 + ".";    
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        // Main method where the program begins.
        public static void main(String[] args) {
            // Instantiate first MyClass object.
            try {
               MyClass1 myobject = new MyClass1 (3456789, 150000);
               // if successful use MyClass1 toString() method.
               System.out.println(myobject);
                         // Catch the exceptions within the main method and print appropriate
                         // error messages.
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
             }I am not sure what is buggy. Everything else is working fine.

  • Overriding toString() method

    hello all,
    in the following class how toString() is overriding?
    class Box {
        public Box(){
        public String toString(){
            return "Hello";
        public static void main(String args[]){
            System.out.println(new Box());
    }even though i am not extending anything.
    how the toString() method of String class is overriding here?
    is it due to Object class?
    thanks
    daya

    even though i am not extending anything.
    how the toString() method of String class is
    overriding here?
    is it due to Object class?Yes, thats it exactly. Even when you do not extend and class, by default every class inherits from the Object class. Since toString is defined in the Object class, you override it when you defing toString with the same signature.

  • Having some problems with toString method.

    Hi well my toString method is fine but what I don't understand is why am I getting the ouput for the toString where I am not supposed to.
    import java.text.DecimalFormat;
        public class Sphere
       //Variable Declarations.
          private int diameter;
          private double radius;
       //Constructor: Accepts and initialize instance data.
           public Sphere(int sp_diameter)
             diameter = sp_diameter;     
             radius =(double)diameter/2.0;
       //Set methods: Diameter
           public void setDiameter(int new_diameter)
             diameter = new_diameter;
             radius = (double) diameter/2.0;
       //Get methods: Diameter
           public int getDiameter()
             return diameter;
       //Compute volume and surface area of the sphere
           public double getVolume()
             return  4 * Math.PI * radius * radius * radius / 3;
           public double getArea()
             return  4 * Math.PI * radius * radius;
       //toString method will return one line description of the sphere
           public String toString()     
             DecimalFormat fmt1=new DecimalFormat("0.###");
             String result = "Diameter : " + fmt1.format(diameter)+ "\tVolume: " + fmt1.format(getVolume()) + "\tArea: " +fmt1.format(getArea());
             return result; // This is fine .. the problem is the driver
    Driver
           public static void main(String[]args)
             Sphere sphere1, sphere2, sphere3;
             sphere1 = new Sphere(10);
             sphere2 = new Sphere(12);
             sphere3 = new Sphere(20);
             System.out.println("The sphere diameter are: "); //Here is the problem  for the output I only want the diameter, but I am getting the toString output here too..
             System.out.println("\tFirst Sphere diameter is: " + sphere1);
             System.out.println("\tSecond Sphere diameter is: "+ sphere2);
             System.out.println("\tThird Sphere diameter is: " + sphere3);
          //Prints the Sphere Volume and  Surface Area.
             DecimalFormat fmt = new DecimalFormat("0.###");
             System.out.println("\nTheir Volume and Surface Area: ");
             System.out.println("\tSphere1: " + "Volume: " + fmt.format(sphere1.getVolume()) + "\tSurface Area: " + fmt.format(sphere1.getArea()));
             System.out.println("\tSphere2: " + "Volume: " + fmt.format(sphere2.getVolume()) + "\tSurface Area: " + fmt.format(sphere2.getArea()));
             System.out.println("\tSphere3: " + "Volume: " + fmt.format(sphere3.getVolume()) + "\tSurface Area: " + fmt.format(sphere3.getArea()));
          //Change the diameter of the sphere.
             sphere1.setDiameter(11);
             sphere2.setDiameter(15);
             sphere3.setDiameter(25);
             System.out.println("\nNew diameter is: ");
             System.out.println("\tFirst Sphere diameter is: " + sphere1);
             System.out.println("\tSecond Sphere diameter is: " + sphere2);
             System.out.println("\tThird Sphere diameter is: " + sphere3);
          //Prints the Sphere Volume and  Surface Area.
             System.out.println("\nTheir Volume and Surface Area: ");
             System.out.println("\tSphere1: " + "Volume: " + fmt.format(sphere1.getVolume()) + "\t\tSurface Area: " + fmt.format(sphere1.getArea()));
             System.out.println("\tSphere2: " + "Volume: " + fmt.format(sphere2.getVolume()) + "\tSurface Area: " + fmt.format(sphere2.getArea()));
             System.out.println("\tSphere3: " + "Volume: " + fmt.format(sphere3.getVolume()) + "\tSurface Area: " + fmt.format(sphere3.getArea()));
          //Using the toString Method.
             System.out.println("\nFirst sphere: " + sphere1);
             System.out.println("\nSecond sphere: " + sphere2);
             System.out.println("\nThird sphere: " + sphere3);
     

    System.out.println("The sphere diameter are: "); //Here is the problem for the output I only want the diameter, but I am getting the toString output here too..
    System.out.println("\tFirst Sphere diameter is: " + sphere1);
    System.out.println("\tSecond Sphere diameter is: "+ sphere2);
    System.out.println("\tThird Sphere diameter is: " + sphere3);
    If you only want the Diameter, than use a formatter and get the diameter like you did when you printed the surface area and volume. Or, print shpere1.getDiameter();
    You have already demonstrated the solution to your problem elsewhere in your code, I think you need to re-read and understand what you have done so far.

  • Plz help.... toString() method

    hi....i came accross this sample of toString method. I was wondering how do i return all the variables instead of dont concat ?Pleas help...
    class ToStringClass {
    String firstName;
    String lastName;
    public ToStringClass(String fname, String lname) {
    this.firstName = fname;
    this.lastName = lname;
    // Override the toString() method
    public String toString() {
    return lastName + ", " + firstName;
    }

    sorry for the misleading question... here is the simple full coding of it
    public class ToStringObjectExample {
        public static void main(String[] args) {
               // Overriding the equals() method
            ToStringClass tsc2 = new ToStringClass("Jane", "Doe");
            System.out.println("Class with toString() method    : " + tsc2);
    class ToStringClass {
        String firstName;
        String lastName;
        public ToStringClass(String fname, String lname) {
            this.firstName = fname;
            this.lastName = lname;
        // Override the toString() method
        public String toString() {
            return lastName + ", " + firstName;
    }the output will be display like :-
    Class with toString() method    : Doe, JaneI was thinking how do i display or print the output directly like below :-
    Doe
    Jane
    , which means that displaying the value of each variable. how do i do the return statement?

  • Which toString() method does System.out.println() call?

    Which toString() method does System.out.println() call? I know that if I did something like System.out.println( new myClass() ) that the toString being called would be that of the myClass class.
    My initial thought about this was that System.out.println() is the equivalent of System.out.println( new Object() ) but I remember trying that in a test program and it gave me a myClass@some_hash_code type of message when adding the new Object() part within the System.out.println().
    Could someone please tell me which toString the System.out.println() statement calls? Also, it would be great if an elaboration follows :).
    Any input woudl be greatly appreciated!
    Thanks in advance!

    s3a wrote:
    My initial thought about this was that System.out.println() is the equivalent of System.out.println( new Object() ) Huh?
    In one method call you pass no parameters in the other method call you pass one parameter. How could you possibly think that they would do the same thing?
    Could someone please tell me which toString the System.out.println() statement calls? Also, it would be great if an elaboration follows :).Yes. The toString of the class of the object which you pass to the method. If that class does not have a toString method it uses the toString method it inherits from the parent class. If the parent class does not have a toString method it uses the one inherited and so and so on all the way up to the Object class.

  • ToString method why its not called implicitly for objects

    class Building { }
    public class Example
    public static void main()
    Building b = new Building();
    String s = (String)b;
    in the 5th Line it shows error that cannot cast building type to string..
    but all classes have the toString method which is called whenever we give the object arguement in System.out.println();
    the following code compiles
    class Building { }
    class Example
    public static void main()
    Building b = new Building();
    System.out.println(b);
    can anyone explain this?

    I get your point about casting.
    but in the println statement when u pass the building object it calls the toString method and generates a new string object
    why does not it do the same in the below code.
    String s = b;// b is a building object
    is the tostring method implicitly called only in println where it expects a string?

  • XML toString method not working as expected.

    Why is the XML.toString method inconsistant?
    var xml:XML = new XML( "<root/>" );
    var xml_withtext:XML = new XML( "<root>a</root>" );
    var xml_withchild:XML = new XML( "<root><child/></root>" );
    trace(xml.toString()); //traces "" (blank)
    trace(xml_withtext.toString()); //traces "a"
    trace(xml_withchild.toString()); //traces "<root><child/></root>"
    If the XML contains only a root node, toString prints nothing.  When it contains text, it prints the text.  That would make sense if toString was printing only the contents of the root node, but if the root node contains a child, it doesn't print "<child/>" as one would expect.  Instead, it suddenly includes the root node as well in the string.  That is inconsistant/unexpected.  For some reason, there is also a separate toXMLString method that consistantly prints the entire XML structure.  Was that some kind of patch since toString doesn't work in a consistant manner, instead opting to sometimes include the root node depending on whether it contains simple or complex content?

    Andrei1:
    1. No, it's not what it is.  No, there aren't hundreds of reasons/dependencies why more descriptive or intuitive conventions are not chosen. In this case, the reason (singular) is spelled out in the E4X spec, and it basically boils down to them naively thinking it would be easier for programmers if the node would just magically return text if that's all it contains.  In other words, they thought it would be simpler for a node to run specialized arbitrary logic to decide what to return, than it would for a programmer to explicitly select what they want by typing ".text".  I see no reason why XML.toString should return anything other than the underlying/original string of characters that originally represented the node in the first place.  If programmers wanted the child text of a node, they should call a method like "getTextContent".  Since an original, unaltered string of XML character had to exist in the first place in order to instantiate an XML object, anything that creates a new string based on arbitrary logic, for whatever reason, has no business existing within the toString method.  For classes that represent data that is not fundamentally a string, any string representation is by definition arbitrary and in that case they can override the universal (i.e. a member of every base Object) toString method.  But for classes that represent strings, toString should return the string they represent, unaltered.
    2.  An AS3 XML object IS an XML-type object, but the AS3 XML class is actually instantiated from String-type data or from  bytes that represent encoded String data (i.e. sequences of known  characters), because XML is very strictly and fundamentally a "markup language" which is essentially a format of a string of characters.  Its rules are based around characters, exact unicode character classes, and a logical ordering of those characters.  XML is logically and fundamentally the kind of data that a String class represents, text, so its converstion to a String instance should be straightforward.   As a string, a "toString" method for a node should return the original string representation of that node from the first character that is part of that XML node to the last character that is part of that node.  XML may contain data the represents anything, but XML itself is a string of characters.  Period.
    3.  There is a universal string method called toString and it's a member of the most basic class "Object" which all other classes inherit from.  Although the technical details are different in different object-oriented langauges, they all tend to have a method like that, whether we're talking about AS3, C#, Java, or JavaScript.  Calling toString on a String returns the string itself.  Calling toString on a class that represents a string, should return the string it represents; not some arbitrary tranformation of that string.  Calling toString on a class that doesn't represent a string, has no default string representation to return, and therefore any string returned is by definition arbitrary.
    4.
    In other words toString() does not return XML at all but an un-interpreted representation that is cast to String
    That's precisely what it DOESN'T do.  Instead of returning the original, un-interpretted representation of the string FROM WHICH THE NODE WAS CONSTRUCTED, it returns some arbitrarily interpretted represention.  It decides whether the XML string is interpretted as complex or simple content, and then it arbitrarily decides to include or not include the outermost tags representing the XML of that node.  The fact remains, the string representation PRECEDES the existance of the XML instance, so toString should not be performing arbitrary logic to construct a brand new string.
    In other languages datatype string can be a totally different animal.
    No, actually a string always refers to a secquence of characters.  Each of those character may contain one or more bytes, they may be contiguous in memory or not, they may be represented by arrays, linked lists, doubly-linked lists, etc. but their logical data is always a sequence of characters.  That is the same in every programming language, and is even codified in the Unicode standards which represents characters in hundreds of different written languages.
    5.
    Again, XML is not a string until application says so and XML in AS3 is not a String but a special object.
    XML is actually a string BEFORE the application says it is XML, since the XML is constructed FROM A STRING.  XML is a special object, which is constructed from, represents, and processes a string.
    I could very easily create a class named "AllCapsSentence" and like "XML", the class itself is not "String", but they logically represent a string of characters and any "toString" method on either of such classes should return the underlying string representation without mangling it.

  • .toString() method is it better to overload or override?

    Whenever I write a class, I make it a practice to override the .toString() method to display the contents of the properties, for logging and debugging purposes. I recently have seen code samples where the .toString() was overloaded: public String toString(String foo){ ...
    I have never run into a problem with over riding toString(). Obviously there isn't an issue overloading it. But It makes me wonder if there is a particular reason not to override? The only thing I can think is that maybe a j2ee container needs to use .toString() and if a serialized bean class is overriden, then it could cause a problem in the container? Or I could see where a debug tool inside an ide might need to use .toString()?
    Is one way better than the other or is it a matter of style?
    Thanks

    With overloading, they might just as well have named toString(String foo) something else like whatever(String foo). It's not a matter of "one way better than the other" nor "style".

Maybe you are looking for

  • Creative Cloud 1.8.0.447 update seems to kill Photoshop CC 2014

    I been using Photoshop CC 2014 on a Macbook Pro 17" since it was released without incident (system was running 10.9.4, now 10.9.5; it has 16 gigs ram and a 500 mb SSD).  In the last few days, I updated Creative Cloud to 1.8.0.447, and that seems to h

  • Does there be any change in the dimensions of the project when published in a web browser ?

    Hello all. I am facing a problem with the dimensions of my project. I need my published project in the web browser must fit in the window without any scrolling. I started my project with the dimensions 1024*540. when I tested it at the initial stage

  • Remove Domain from Search indexes

    Interesting dilemma, I've created a site through iWeb, bought the domain from godaddy and hosted on mobile me for now at least. I"m using this site to communicate with friends and family about volunteer work I"ll be doing in an unsecure, developing c

  • I lost my ipod5 receipt how can i recover it?

    I deleted my e-receipt e-mail. I bought an iPod 5 from Apple online.. it broke..want to get it fixed as still under warranty. How do i contact apple to do this?

  • How do I make a Self Contained Project?

    I'm doing a huge digitization project that involves digitising interviews. My project is full of Bins with the relevant captured footage inside, how can I take one of these bins and either copy it or make it a self contained project so I can take it