Returning null in a function that should return an integer

The code identifies the integer that is closest to 0 in an array and if there are 2 or more values that meet this condition the return value should be null.The problem is that when I make the condition to return null it displays an error because the function is supposed to return an integer.

    static int function(int [] arr){
    int closest=arr[0];
    for(int i=1;i<arr.length;i++){
        if(Math.abs(arr[i])<closest){
            arr[i]=closest;
        }
        else if(arr[i]==closest){
            return null;
        }
    }
    return closest;
}

I am very new to Java (learned Python before),if there is a better/more eficient approach to this code please share.

Answer:1

You can convert the return type to Integer which can hold null and will auto box and unbox to an int:

static Integer function(int [] arr){
    int closest=arr[0];
    for(int i=1;i<arr.length;i++){
        if(Math.abs(arr[i])<closest){
            arr[i]=closest;
        }
        else if(arr[i]==closest){
            return null;
        }
    }
    return closest;
}

However this is probably not the best solution. You could instead return Integer.MAX_VALUE to signify that two of the elements were equidistant from zero. This depends on how you plan to handle the case where there are two elements of equal distance to 0.

Answer:2

If you need to support null (e.g. Python's None) then you should return the wrapper type Integer.

static Integer function(int [] arr) {
    // ...
}
Answer:3

I have recently been setting up mobile apps to work with my meteor server. As a part of this I have to pass the meteor web app data from android. Unfortunately I have been receiving a error that tells ...

I would like to create 5-6 classes,I am storing values in hashmap in 1st class & I would like to call it from 4th,5th & 6th class.How to get this any snippets or example to implement this ...

I am using the Kubernetes-client java client to create Deployments on a Kubernetes cluster. THis is the code Deployment deployment = new DeploymentBuilder() .withNewMetadata() ....

I have a Notes App which contain DB, I need to use this Notes App as lib or module in My two parent apps, how can I use this in my two apps? AAR: If I am using .aar means is there possibility to ...