0

I have a have a class that has a method which takes a string. Then I have a method which returns the value of the above method. When ever I get the return value in my main class and print it the printed value is "ExamQuestion@143c8b3". How do I get it to print correctly?

Thanks

logtech
  • 5
  • 5
  • It would help if you provided an example of your code that isn't working, by which I mean strip your code of everything that isn't required to show your problem and then place it in the body of the question. – Amndeep7 Feb 07 '13 at 05:12

5 Answers5

2

You should have ExamQuestion overriding toString().

Luis
  • 1,294
  • 7
  • 9
2

Whenever you get the format "@" this is the default format of an object's toString() method.

Calling System.out.println(question); calls ExamQuestion.toString(). If the method isn't overridden, the version in the super class will be called, in this case it will be Object's version.

So that's why you get ExamQuestion@143c8b3.

To fix this, put the following method in your ExamQuestion class:

public String toString() {
    // return a string that means something here
}
Brad
  • 9,113
  • 10
  • 44
  • 68
1

The output you are seeing is how java represents objects as strings.

The default behavior is:

this.getClass().getSimpleName() + "@" + Integer.toHexString(this.hashCode());

If you want the string representation of your object to be more clear, you should override the toString() method in your class.

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
1

That is the default behaviour as explained by @ValekHalfHeart in his answer.

If you want to print your objects stuff then you need to override toString method in your class.

Say I have this code:

class MyClass{
   int a,b;
}

So when I make an object of this class and pass it to println:

public static void main(String args[]){
  MyClass m = new MyClass();
  m.a = 20;
  m.b = 30;
  System.out.println(m);
}

It will print something like MyClass@143c8b3 as is your case.

So now if I want that whenever I pass my object to println it should print something else like values of my variables a and b should be printed.

Then I should override tostring method in MyClass:

class MyClass{
   int a,b;

   public String toString(){
     return "MyClass values: a = "+a+" and b = "+b;
   }
}

So now when I say this

public static void main(String args[]){
  MyClass m = new MyClass();
  m.a = 20;
  m.b = 30;
  System.out.println(m);
}

Its going to print MyClass values: a = 20 and b = 30

So you have to do that for your ExamQuestion class

Abubakkar
  • 15,488
  • 8
  • 55
  • 83
0

All classes inherit (implicitly) from Object, which has the toString() method, the implementation of which is producing the output you're seeing.

To have a meaningful String representation, you must override this method to provide an implementation that's suitable for your class.

Bohemian
  • 412,405
  • 93
  • 575
  • 722