0

I'm new to Java, and currently learning how methods work in Classes. I wrote a simple method that should return a String value, but when i concatenated it with a int value it still works.

I tried flipping the return value to start off with the int and that also worked. Does java know to convert the int value into a String value?

public class MyOwnJavaProject 
{

    int favoriteNumber;

....
// This method worked
public String showFavNumber()
    {
        return "My favorite number is " + this.favoriteNumber;
    }

// This method also worked
public String showFavNumber()
    {
        return this.favoriteNumber + " is my favorite number";
    }

1 Answers1

0

You are returning a String in both. When you + (concatenate) a String and an int it returns a String. This would not work:

public String showFavNumber()
{
    return this.favoriteNumber;
}

but this would:

public int showFavNumber()
{
    return this.favoriteNumber;
}
brso05
  • 13,142
  • 2
  • 21
  • 40