首页 > 解决方案 > Java - Why void when I'm storing value in variable

问题描述

So, the question is. If I'm calling method guess from class - Player and it is a void-type method without return statement in it, how come I'm able to store result of number = (int)(Math.random() * 10) in number variable for 3 different objects (p1, p2, p3)?

I'm little confused about when should I use return statement or void-type methods, because if number = (int)(Math.random() * 10) is giving some results which I want to use, why then I don't need to return this results from a method to pass them to the number variable which I declared in int number = 0;

    public class Player {
       int number = 0;

       public void guess() {
          number = (int)(Math.random() * 10);
          System.out.println("I'm guessing " + number);
       }
    }

标签: javavoid

解决方案


A void method does not return anything, but it still allows you to do things. (Print to the console, modify variables etc) The void keyword just means that it doesn't return a value. (In void methods you can still use a blank return; to end the method) And because you are modifying your number variable in the GuessGame object the changes you make will stay even though you don't return a variable. Try this simple test to see what I mean:

//In your GuessGame class
int number = 0;
public void foo() {
    number++;
}

public static void main(String[] args) {
    GuessGames games = new GuessGames();
    games.foo();
    System.out.println(games.number);
    //Outputs 1
}

docs for the return statement


推荐阅读