.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".

Similar Messages

  • Constructing toString method??

    could anybody how to construct a toString method to display my content overloading constructor.
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.*;
    import java.lang.String;
      public class TextAnalysis{
        public String refAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        public int[] amountOfAlpha = new int[26];         
    public TextAnalysis( String newInputData )
       try
        FileReader fr = new FileReader(newInputData);
        BufferedReader br = new BufferedReader(fr);
        int charOfAlpha;
        while((charOfAlpha = br.read()) != -1 )
          char UpperChar = Character.toUpperCase((char)charOfAlpha);
          //System.out.println( UpperChar );
          int valueOfAlpha = Character.getNumericValue((char)UpperChar)-10;
          //System.out.println( valueOfAlpha );
          if( valueOfAlpha >= 0 && valueOfAlpha <= 25 )
          amountOfAlpha[valueOfAlpha] = amountOfAlpha[valueOfAlpha] + 1;
          //System.out.println ( amountOfAlpha );
         fr.close();
        catch(FileNotFoundException e)
          System.out.println("File not found");
        catch(IOException e)
          e.printStackTrace( );
    public char highestFrequencyCharacter()
      char mostLetter = '-';
      int maxIndex = 0;
      for( int i = 1; i < amountOfAlpha.length ; i++ )
         if ( amountOfAlpha[i] > amountOfAlpha[maxIndex] )
            maxIndex  =  i;                                           
        mostLetter = refAlpha.charAt(maxIndex);
        return mostLetter;
    public char lowestFrequencyCharacter()
      char lessLetter = '-';
      int lessIndex = 0;
      for( int i = 1; i < amountOfAlpha.length ; i++ )
         if ( amountOfAlpha[i] < amountOfAlpha[lessIndex] )
            lessIndex  =  i;                                           
        lessLetter = refAlpha.charAt(lessIndex);
        return lessLetter;
    public String toStrng()
      return xxxxx;// i stuck on here.
    }

    my programming should look sth like that ...could u
    give me some idea"sth" means "something", right ?
    I would like to use my toString method
    to display >>
    Sth like
    A 26 // the frequency of the character
    B 25 //
    C 21 //
    DSo why don't you do it ? You have written your class so you're best to know how these informations you want displayed can be fetched.
    Create a StringBuffer, append() other strings (I suppose that'll involve some kind of loop), and when you're finished, return the StringBuffer.toString().

  • ToString method??

    could anybody how to construct a toString method to display my content overloading constructor.
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.*;
    import java.lang.String;
    public class TextAnalysis{
    public String refAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public int[] amountOfAlpha = new int[26];
    public TextAnalysis( String newInputData )
    try
    FileReader fr = new FileReader(newInputData);
    BufferedReader br = new BufferedReader(fr);
    int charOfAlpha;
    while((charOfAlpha = br.read()) != -1 )
    char UpperChar = Character.toUpperCase((char)charOfAlpha);
    System.out.println( UpperChar );
    int valueOfAlpha = Character.getNumericValue((char)UpperChar)-10;
    //System.out.println( valueOfAlpha );
    if( valueOfAlpha >= 0 && valueOfAlpha <= 25 )
    amountOfAlpha[valueOfAlpha] = amountOfAlpha[valueOfAlpha] + 1;
    //System.out.println ( amountOfAlpha );
    fr.close();
    catch(FileNotFoundException e)
    System.out.println("File not found");
    catch(IOException e)
    e.printStackTrace( );
    public char highestFrequencyCharacter()
    char mostLetter = '-';
    int maxIndex = 0;
    for( int i = 1; i < amountOfAlpha.length ; i++ )
    if ( amountOfAlpha[i] > amountOfAlpha[maxIndex] )
    maxIndex = i;
    mostLetter = refAlpha.charAt(maxIndex);
    return mostLetter;
    public char lowestFrequencyCharacter()
    char lessLetter = '-';
    int lessIndex = 0;
    for( int i = 1; i < amountOfAlpha.length ; i++ )
    if ( amountOfAlpha[i] < amountOfAlpha[lessIndex] )
    lessIndex = i;
    lessLetter = refAlpha.charAt(lessIndex);
    return lessLetter;
    public String toStrng()
    return xxxxx;// i stuck on here.
    }

    Could you please stop that:
    http://forum.java.sun.com/thread.jspa?threadID=706906&tstart=0
    http://forum.java.sun.com/thread.jspa?threadID=706907&tstart=0
    http://forum.java.sun.com/thread.jspa?threadID=706909&tstart=0

  • 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

  • In session and call tansaction methods, which is better . why?

    hi
    in session and call tansaction methods, which is better . why?

    see the link:
    <a href="http://www.itcserver.com/blog/2006/06/30/batch-input-vs-call-transaction/">batch inpunt VS call transaction</a>
    "The most important aspects of the session interface are:
    <b>Asynchronous processing</b>
    Transfer data for multiple transactions
    Synchronous database update. During processing, no transaction is started until the previous transaction has been written to the database.
    A batch input processing log is generated for each session
    Sessions cannot be generated in parallel. The batch input program must not open a session until it has closed the preceding session.
    The most important features of CALL TRANSACTION USING are:
    <b>Synchronous processing</b>
    Transfer of data from an individual transaction each time the statement CALL TRANSACTION USING is called
    You can update the database both synchronously and asynchronously. The program specifies the update type.
    Separate LUW (Logical Units of Work) for the transaction. The system executes a database commit immediately before and after the CALL TRANSACTION USING statement.
    No batch input processing log"
    I hope I have been able to help you.
    cordial greetings.

  • 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.

  • Which method has a better performance ?

    Hello !
    I'm using entity framework , and I have several cases where I should run a query than return some parent items , and after I display these parents and the related children  in one report.
    I want to know which of these methods have the better performance : ( or is there any other better method ??? )
    Method1: (the childs collection are loaded later , using lazy loading)
    Dim lista as IQueryable(Of MyObj) = (From t In context.MyObjs Where(..condition..) select t).Tolist
    Method2:
    Dim lista as IQueryable(Of MyObj) = (From t In context.MyObjs Where(..condition..) _
    .Include(Function(t2) t2.Childs1) _
    .Include(Function(t2) t2.Childs2) _
    .Include(Function(t2) t2.Childs2.Child22) _
    .Include(Function(t2) t2.Childs1.Childs11) _
    .Include(Function(t2) t2.Childs1.Childs12) _
    Select t).ToList
    Method3:
    Dim lista as IQueryable(Of MyObj)
    Dim lst= (From t2 In context.MyObjs Where(..condition..) Select New with _
    { .Parent=t2
    .ch1=t2.Childs1 _
    .ch2=t2.Childs2 _
    .ch21=t2.Childs2.Child21) _
    .ch11=t2.Childs1.Childs11) _
    .ch12= t2.Childs1.Childs12 _
    ).ToList
    lista=lst.Select(Function(t2) t2.parent)
    I noticed that the first method cause the report to open very slow. Also I read somewhere that Include() cause repeat of parent items?
    But anyway I want a professional opinion in general for the three methods.
    Thank you !

    Hello,
    As far as I know, the Entity Framework offers two ways to load related data after the fact. The first is called lazy loading and, with the appropriate settings, it happens automatically. In your case, your first method uses the last loading, while the second
    and third are the same actually, both of them are Eager Loading. (In VB, if you could check use code as “DbContext.Database.Log = Sub(val) Diagnostics.Trace.WriteLine(val)” to see the actually generated sql statement, you could see the third and second query
    would generate a join syntax). Since you mentions, the lazy loading way is low performance, you could use either the second or third one.
    >>Also I read somewhere that Include() cause repeat of parent items?
    For this, nor sure if you worry it would firstly use lazy loading and then use eager loading, however, in my test, I do not see this behavior, the Entity Framework seems to be smart enough to use one mode to load data at the same time. Or you could disable
    its lazy loading when using eager loading:
    context.ContextOptions.LazyLoadingEnabled = false
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to enforce developers to override toString() method

    Hi,
    Right now we are in design stage of our application. I want that all our BO classes should override toString(), equals() and hashCode() methods.
    We expect that our application would be running for next 5 to 10 years, and so looking for ways to enforce these rules to developers.
    One way to do is let ant script handle such validations. Another way could be using PMD to enforce rules.
    These could be good ways of doing this, but my manager doesnot quite like to depend on external tools like these ... as 5 years down the line you donot know state of these tools.
    Can someone suggest if java provides any such provision ...
    If someone has some smart solution do let me know ... your help is much appreciated ... and thanks in advance.
    Regards,
    Rana Biswas

    This is interesting.
    toString() method is already implemented in class Object, which is inherited by all other class.
    What happens if we make toString() method abstract. I tried it and compiler allows to do it ... was wondering if it would have any side effect.
    Regards,
    Rana Biswas

  • 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.

Maybe you are looking for

  • My apple tv is not streaming video without stopping

    When streaming films from my mac air to apple TV  the internet steaming is non stop But the apple TV stopped while it is buffering. So although the film runs without stopping on the Mac Air screen it keeps stopping when being mirrord on the HD Tv via

  • Connecting an older MacBook Pro to Current Dual (Mac) Display Monitors

    I am thinking of buying dual displays (24-inch) and I have a MacBook Pro I bought in 2007: It's an OS X (10.4.11). I'd like to be able to connect this laptop to the dual displays, but I've read that there may be issues with connectivity with the "old

  • New Question for ABAP....( &1 and &2 )....

    Dear Sir And Madams, Cool Hii to all of you....Here once again i have stuck with a little probem... kindly help me out if you had solutons.... In one module pool coding i have found one strange thing and it is that :   LOOP AT &1.     &1-SEL = &2.   

  • Passing XML into JSP Variable

    I want to do the following <% response.setContentType("text.xsl"); String something = ""+<xsl:value-of select='@id' />+""; %> But seems like the xsl doesn't render Can someone point me in he right directions

  • ASP and SQL Server Database

    My AW7 pieces send user data to asp pages which relay the data on to a SQLServer 2000 database. All works well with one exception: when a new record is created, any spaces in the string containing the user's name are deleted. When AW7 sends the varia