Tom Bacon
Tom Bacon

Reputation: 3

Difference between the usage of void and int in this code

Currently a beginner, I wrote a simple program which uses getters and return values (current course). I'd like to ask when should I use the void solution and the int solution, if both gives me the same outcome?

I really hope the formatting isn't too terrible.

class Database {
    String name;
    int age;

    String getName() {
        return name;
    }

    int getAge() {
        return age;
    }

    int yearsPlusFifty() {
        int year = age + 50;
        return year;
    }

    void plusFifty() {
        int year2 = age + 50;
        System.out.println(year2);
    }
}

public static void main(String args[]) {

    Database person1 = new Database();
    person1.name = "Josh";
    person1.age = 30;

    int year = person1.yearsPlusFifty();
    System.out.println("The age plus 50 is: " + year);

    person1.plusFifty();
}

Upvotes: 0

Views: 122

Answers (2)

Vasu
Vasu

Reputation: 22412

Basically, void should be used when your method does not return a value whereas int will be used when your method returns int value.

Now coming to your methods, they both are not same, they are doing two different things:

int yearsPlusFifty() - adding 50 and returning int value

void plusFifty() - better rename to printPlusFifty() - this method does both adding plus printing as well

int yearsPlusFifty() {//only adding and returning int value
    int year = age + 50;
    return year;
}

  void printPlusFifty() {//adding + printing
        int year2 = age + 50;
        System.out.println(year2);
    }

Upvotes: 0

NP3
NP3

Reputation: 1264

Use the int method (yearsPlusFifty) as that one has one responsibility - to calculate the value. Println in plusFifty is a side effect, which is not desirable. Keep the responsibilities of calculating and printing separate (makes it more reusable, testable, and easier to understand).

Upvotes: 3

Related Questions