-2
class Jatin{
    int value = 9;
    public static void main(String args[]){
        Jatin obj = new Jatin();
        String str = new String("Hello");

        System.out.println(obj);//prints unique id why
        System.out.println(str);//prints string value why
    }
}

How to modify this code and use obj object of class Jatin to print all its data members i.e. print out the value =9. Whereas in String str sop print the value . Why?

azro
  • 53,056
  • 7
  • 34
  • 70

2 Answers2

2

You need to create a getter in order to print them, or just access the specific fields directly when you print.

You could also just simply implement/override the toString method if you want a way of printing all members with one call.

For example:

class Jatin {
  String name = "Jatin";
  int value = 9;

  @Override
  public String toString() {
      System.out.println("Name: " + name + "\n" + " value: " + value);
  }
}

Or if you only need a specific value just call on the field.

Jatin obj = new Jatin();
System.out.println(obj.value); // will print the value

The reason why you only get unique hash is because you don't have toString()

Jojo Narte
  • 2,767
  • 2
  • 30
  • 52
1

Printing an instance of a class directly returns className@hashcode of that object

If you need to access the attributes of an object, you need to access them using dot operator.

In your case, obj.value i.e System.out.println(obj.value);

hsnsd
  • 1,728
  • 12
  • 30