1

I'm trying just to print a simple thing that says : Hola hi hello, but for some reason it is printing what I want but I get some numbers on my output

Sorry if its an easy thing to find or fix but I'm just starting with java so I'm a complete noob.

My files look like:

Example.java

public class Example {
    public static void main(String[] args){

            Hola ho = new Hola("hola");

            System.out.printf("%s hi hello", ho);
    }
}

Hola.java

class Hola {
    public String name;

    public Hola(String name){
        this.name = name;

    }
}

Output: Hola@7852e922 hi hello%

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Fidel Castro
  • 277
  • 2
  • 4
  • 10

2 Answers2

4

You have to use ho.name:

System.out.printf("%s hi hello", ho.name);

because ho will print the object reference and not the name.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    Thank you, this fixed my issue :) so do you know what those numbers are? are they just the memory that the variable holds ? – Fidel Castro Apr 28 '17 at 17:59
  • @FidelCastro this question already answered here http://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4 read this and you will understand more :) – Youcef LAIDANI Apr 28 '17 at 18:02
1

You should override the toString() method of your Hola class:

class Hola {
    public String name;

    public Hola(String name){
        this.name = name;

    }
    @Override
    public String toString()
    {
        return this.name;
    }
}
brso05
  • 13,142
  • 2
  • 21
  • 40
  • is this a better practice or has a better performance than doing this: System.out.printf("%s hi hello", ho.name); – Fidel Castro Apr 28 '17 at 17:58
  • It really depends on why and how you are using your `class`. If it makes sense to `return` the `name` in the `toString()` method of the `class` then I would do it the way I have it...At the very least you should probably make your variable private and make a `getter` and `setter` for it unless you have a specific reason for making it `public`. – brso05 Apr 28 '17 at 19:28