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.

Similar Messages

  • 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

  • Overriding toString method of entrySet() in LinkedHashMap

    Hi all,
    I got a LinkedHashMap which return a Set by entrySet() method. When I print the String represantation of the returned Set, I receive something like [key=value, key=value, key= value]. I, however, would like to override toString method so that I can implement my own representation of the Set class which is returned by entrySet() method. How can I do that if it's possible?

    i believe what Peter was saying was to overrider the Set (in your case...the concrete LinkedhashSet class)
    you're not implementing the add, get, contains, etc..function..you're extending it.
    after extending it..you can overide any public and protected method...any other method not overide is still there for you to use.
    so you would have something like this
    public class MyLinkHashSet extends LinkHashSet{
        public String toString(){
             return a String representation you want 
        public Object getMyObject(){ return myObject; }  // your own method
       // you still have all of the other LinkHashSet methods to use
    }

  • 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

  • When and why do we override toString() method

    public class BobTest {
            public static void main (String[] args) {
              Bob f = new Bob("GoBobGo", 19);
              System.out.println(f); // if i put s.o.p("hello"); the overridden toString doesnt get called, y so ?
         class Bob {
            int shoeSize;
            String nickName;
            Bob(String nickName, int shoeSize) {
              this.shoeSize = shoeSize;
              this.nickName = nickName;
            public String toString() {
               return ("I am a Bob, but you can call me " + nickName +
                       ". My shoe size is " + shoeSize);
         }

    masijade. wrote:
    To get a meaningful String representation of your Object.And just to further the point
    @OP: In answer to your original question: almost always.
    I generally don't regard a class as complete until I've implemented toString() -- or, at the very least, displayed it with println() and determined that the default representation is fine.
    Same goes for equals() and hashCode().
    Winston

  • 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

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

  • ...is not abstract and does not override abstract method compare

    Why am I getting the above compile error when I am very clearly overriding abstract method compare (ditto abstract method compareTo)? Here is my code -- which was presented 1.5 code and I'm trying to retrofit to 1.4 -- followed by the complete compile time error. Thanks in advance for your help (even though I'm sure this is an easy question for you experts):
    import java.util.*;
       This program sorts a set of item by comparing
       their descriptions.
    public class TreeSetTest
       public static void main(String[] args)
          SortedSet parts = new TreeSet();
          parts.add(new Item("Toaster", 1234));
          parts.add(new Item("Widget", 4562));
          parts.add(new Item("Modem", 9912));
          System.out.println(parts);
          SortedSet sortByDescription = new TreeSet(new
             Comparator()
                public int compare(Item a, Item b)   // LINE CAUSING THE ERROR
                   String descrA = a.getDescription();
                   String descrB = b.getDescription();
                   return descrA.compareTo(descrB);
          sortByDescription.addAll(parts);
          System.out.println(sortByDescription);
       An item with a description and a part number.
    class Item implements Comparable     
          Constructs an item.
          @param aDescription the item's description
          @param aPartNumber the item's part number
       public Item(String aDescription, int aPartNumber)
          description = aDescription;
          partNumber = aPartNumber;
          Gets the description of this item.
          @return the description
       public String getDescription()
          return description;
       public String toString()
          return "[descripion=" + description
             + ", partNumber=" + partNumber + "]";
       public boolean equals(Object otherObject)
          if (this == otherObject) return true;
          if (otherObject == null) return false;
          if (getClass() != otherObject.getClass()) return false;
          Item other = (Item) otherObject;
          return description.equals(other.description)
             && partNumber == other.partNumber;
       public int hashCode()
          return 13 * description.hashCode() + 17 * partNumber;
       public int compareTo(Item other)   // OTHER LINE CAUSING THE ERROR
          return partNumber - other.partNumber;
       private String description;
       private int partNumber;
    }Compiler error:
    TreeSetTest.java:25: <anonymous TreeSetTest$1> is not abstract and does not over
    ride abstract method compare(java.lang.Object,java.lang.Object) in java.util.Com
    parator
                public int compare(Item a, Item b)
                           ^
    TreeSetTest.java:41: Item is not abstract and does not override abstract method
    compareTo(java.lang.Object) in java.lang.Comparable
    class Item implements Comparable
    ^
    2 errors

    According to the book I'm reading, if you merely take
    out the generic from the code, it should compile and
    run in v1.4 (assuming, of course, that the class
    exists in 1.4). I don't know what book you are reading but that's certainly incorrect or incomplete at least. I've manually retrofitted code to 1.4, and you'll be inserting casts as well as replacing type references with Object (or the erased type, to be more precise).
    These interfaces do exist in 1.4, and
    without the generics.Exactly. Which means compareTo takes an Object, and you should change your overriding method accordingly.
    But this raises a new question: how does my 1.4
    compiler know anything about generics? It doesn't and it can't. As the compiler is telling you, those interfaces expect Object. Think about it, you want to implement one interface which declares a method argument type of Object, in several classes, each with a different type. Obviously all of those are not valid overrides.

  • Overriding redo method in drawing arrows

    I have to undo and redo of path and arrows to them.at a time i need only either left arrow undo or right arrow undo depending on the direction in which path is drawn ie if its frm left to right then arrowhead left
    and if its from right to left tthen arrowheadtright.
    Undo is ok But problem comes with redo.Since if the last drawn path is from left to right then arrowright becomes null.pls suggest me a method overriding redo method for left and right arrows
    private void redoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
      try { m_edit.redo(); }
            catch (CannotRedoException cre)
            { cre.printStackTrace(); }
    drawpanel.repaint();
    undoButton.setEnabled(m_edit.canUndo());
    redoButton.setEnabled(m_edit.canRedo());  
    private void undoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
            try { m_edit.undo(); }
             catch (CannotRedoException cre)
             { cre.printStackTrace(); }
             drawpanel.repaint();
             undoButton.setEnabled(m_edit.canUndo());
             redoButton.setEnabled(m_edit.canRedo());
    class Edit extends AbstractUndoableEdit {
           protected Vector drawarc;
          protected Curve path;
          protected Vector vectlabel;
          protected drawlabel labelarc;
         protected Vector arrowheadleft;
         protected drawArrowHeads arrow1;
         protected Vector arrowheadright;
         protected  drawArrowHeadsecond arrow2;
           public Edit( Vector drawarc, Curve path ,Vector vectlabel,drawlabel labelarc,Vector arrowheadleft,drawArrowHeads arrow1,Vector arrowheadright,drawArrowHeadsecond arrow2)
              this.drawarc = drawarc;
              this.path = path;
                    this.vectlabel=vectlabel;
                    this.labelarc=labelarc;
                    this.arrowheadleft=arrowheadleft;
                    this.arrow1=arrow1;
                    this.arrowheadright=arrowheadright;
                    this.arrow2=arrow2;
         public void undo() throws CannotUndoException {
              drawarc.remove(path);
                    vectlabel.remove(labelarc);
                    arrowheadleft.remove(arrow1);
                    arrowheadright.remove(arrow2);
         public void redo() throws CannotRedoException {
              drawarc.add( path);
                    vectlabel.add(labelarc);
                   // arrowheadleft.add(arrow1);
                   // System.out.println("The arrowheadleft vector inside Edit method contains "+arrowheadleft.toString());
                   arrowheadright.add(arrow2);
                   System.out.println("The arrowheadright vector inside Edit method contains "+arrowheadright.toString());
             public boolean canUndo() {
              return true;
         public boolean canRedo() {
              return true;
         public String getPresentationName() {
              return "Add Arc";
    m_edit=new Edit(drawarc, path , vectlabel, labelarc, arrowheadleft, arrow1, arrowheadright, arrow2);
    undoButton.setText(m_edit.getUndoPresentationName());
    redoButton.setText(m_edit.getRedoPresentationName());
    undoButton.setEnabled(m_edit.canUndo());
    redoButton.setEnabled(m_edit.canRedo());

    ..arrowright becomes null..Check for null value. If null, then do nothing with it.

  • Overriding a method

    Hi All,
    I need to override this method with company.
    Here is the code.
    I appreciate the response .
    public ArrayList getAllBillableCompaniesWithRatesByPlatform(
                   Platform p) throws AppException {
              ArrayList companies = null;
              ArrayList rates = null;
              try {
                   companies = getAllBillableCompanies(
                             p.getName());
                   rates = getDAO().getArcaRatesByPlatform(
                             new Integer(p.getIdPlatform()).toString());
                   Iterator companyIter = companies.iterator();
                   // Loop through all companies to calculate
                   while (companyIter.hasNext()) {
                        BillableCompany company = (BillableCompany) companyIter.next();
                        // Get Rates
                        int iRate = rates.indexOf(new Rate(
                                  company.getCompanyCode(), "", ""));
                        Rate rate = null;
                        for (; iRate >= 0 && iRate < rates.size(); iRate++) {
                             rate = (Rate) rates.get(iRate);
                             if (rate.getCompcode().equalsIgnoreCase(
                                       company.getCompanyCode())) {
                                  if (company.getRates() == null)
                                       company.setRates(new ArrayList());
                                  company.getRates().add(rate);
                             } else {
                                  break;
              } catch (Exception e) {
                   throw new AppException("Failed getting companies with rates", e);
              return companies;
    Thanks
    Smith

    public ArrayList getAllBillableCompaniesWithRatesByPlatform(
    Platform p) throws AppException {
    ArrayList companies = null;
    ArrayList rates = null;
    try {
    companies = getAllBillableCompanies(
    p.getName());
    rates = getDAO().getArcaRatesByPlatform(
    new Integer(p.getIdPlatform()).toString());
    Iterator companyIter = companies.iterator();
    // Loop through all companies to calculate
    while (companyIter.hasNext()) {
    BillableCompany company = (BillableCompany) companyIter.next();
    // Get Rates
    int iRate = rates.indexOf(new Rate(
    company.getCompanyCode(), "", ""));
    Rate rate = null;
    for (; iRate >= 0 && iRate < rates.size(); iRate++) {
    rate = (Rate) rates.get(iRate);
    if (rate.getCompcode().equalsIgnoreCase(
    company.getCompanyCode())) {
    if (company.getRates() == null)
    company.setRates(new ArrayList());
    company.getRates().add(rate);
    } else {
    break;
    } catch (Exception e) {
    throw new AppException("Failed getting companies with rates", e);
    return companies;
    }Wat you said is right I am sorry for that.
    I am not clear with the quuestion but the code is getting platform but wat I need to do is if I am overriding company I need to get the firmid and Mnemonic.
    Hope I am clear now.

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

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

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

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

  • HELP: Inheritance question: Overriding a method.

    Hi all.
    I have one class: BatchJob.java which defines the following method:
    (1) protected void handleException(Exception e) {
         setInitError( true );
         printTrace(getClass().getName(), "*** ERROR: " + e.toString());
         createMailError(e);
    Another class JBDCBatchJob.java which extends BatchJob, overrides the previous method like this:
    (2) protected void handleException(SQLException sqlEx) {
         setInitError( true );
         printTrace(getClass().getName(), getSqlQuery(), sqlEx);
         createMailError(getSqlQuery(), sqlEx);
    where getSqlQuery() is a getter for a String member field which contains the last SQL query sent to the JDBC Driver.
    In another class (say SimpleJDBCBatchJob) which extends JDBCBatchJob, I've got the following code fragment:
    try {
    // statements that may throw SQLException or in general Exception
    catch (Exception e) {
    handleException( e );
    I have realized that the method invoked by the JVM when an SQLException is thrown in SimpleJDBCBatchJob is (1), that is, the "handleException" defined in BatchJob and not that in JDBCBatchJob which it should (or at least, that's what I meant). Why is it? Is it possible to accomplish this without having to rename the method (2), I mean, using method overriding? Any idea would be highly appreciated. THANKS in advance.

    You didn't override the method handleException in JBDCBatchJob, you just overloaded it. So int JBDCBatchJob, you actually had two versions of handleException, one that took a parameter of the type Exception, one that took a parameter of the type SQLException.
    So, in SimpleJDBCBatchJob, you need to have a catch block like
    try {
    // statements that may throw SQLException or in general Exception
    catch (SQLException sqle) {
    handleException( sqle );
    catch (Exception e) {
    handleException( e );
    This would call your handleException in BatchJob if a general exception was thrown, and the handleException in JBDCBatchJob if a SQLException was thrown from the try block.
    Hope that makes things clearer for you.
    Alan

Maybe you are looking for

  • I can not get itunes to open on Windows 7...

    I just got a new iPhone and wanted to back up my old iPhone to my computer one more time before switching over...Two hours later I still can not get iTunes to open.  I have two different acounts on my computer, iTunes will load on the secondary accou

  • Delete of Element in Form for COPA line item report

    Hello I would like to change a form used for a COPA line item report - delete an element, which has been included for years. Unfortunately I got message, that 'You cannot delete, because element xxx is dependent'. If I insert a new element if have no

  • DM - Meter Reading Workflow functionality

    Hi all, I have a customer's requirement that the estimated MR should be "corrected" automatically in case the next actual MR arrives and it is less then the estimation done before. Can anybody help me via the customizing and the development (if any r

  • MPEG -2 Blu-Ray more accurate file size reading in Encore than H.264 Blu-Ray???

    Hi, I just read on Kenstone.com that if you encode a MPEG-2 Blu-Ray instead of an H.264 Blu-Ray, Encore will give you a much closer and more accurate file size reading. Is this true? Encore CS 5.1

  • Need to print mailer info always on even numbered page

    Post Author: LaurenP CA Forum: General Good morning,I'm currently using Crystal Reports 8.5 (I thought I was on 9.0) and am trying to get a report to always print the mailing information on an even numbered page.Here  is the deal.  The report for the