using void methods in log method

1.5k views Asked by At

In MainActivity class:

Log.i("Game ends! ","" + object1.winner()+ object2.winner());

In Game class:

public void winner() {
    if(this.points!=0) {
        Log.i("Winner is", this.objectName);
    }
}

Error is: '+ operator can no be applied to java.lang.String,void

As per the expertise of the given answers users I have done this.

public String winner() {
    if(this.points!=0) {
        return this.name;
    }
}

error: missing return statement

1

There are 1 answers

8
Bryan On BEST ANSWER

The void keyword is not an object or a variable, all it does is specify that a method does not return anything. So the following line means that the function will return void (i.e. nothing):

public void doSomething() {}

Therefore, using the method Log.i() to print nothing is not possible. This method expects two String objects, which it can print to the logcat. The only reason you can use an int is because of the way Java handles String concatenation; it automatically converts any primitive type (boolean, int, float, etc.) to a String when using the + operator.


The reason the Log methods expects two String objects is simply to maintain legibility in logcat. The first parameter is meant to be a TAG variable, which is usually the name of the Class that is calling the method. This is usually done by creating a static value in each class:

private static final String TAG = MyActivity.class.getSimpleName();

In this way, you can use the Log methods as follows:

Log.i(TAG, "Log information…");

Which will result in a more uniform message written to logcat.


So, with this information, the question remains; what are you trying to output to logcat?

If you just want to output that the method was called, than simply call the Log statement before (or after) the method call:

Log.i(TAG, "doSomething() called");
doSomething();

Otherwise, if you actually expect your method to return a printable result, then you must return something other than void. Either a String, a primitive type, or an Object that can be printed using the toString() method.