Hi, Welcome to the Practicehouse. It’s one of the most common Java interview questions even I got this from also the same source “HIRING TEAM”. As you all know already I shared my personal experience with you guy’s in this practice house.

Let’s talk about this post. In this post, I am gonna share with you how to write a Java program to find the Integer Number in a given array that is closest to zero. Mentioned below is the snippet from a hiring team.

In the question, they stated that we have to implement a method to return the integer number in a given array that is closest to zero. Read carefully they also mentioned that if a number is positive and negative we should pick the positive number.

1 2 3 4 5 6 7 8 |
public static int getClosestToZero(int[] a) { /* Please implement this method to return the integer number in a given array that is closest to zero. If there are two equally closest to zero elements like 2 and -2 consider the positive element, i.e. 2, to be "closer" to zero. */ } |

Clone / Download the Sample Project from GitHub : Download / Clone Sample Project

##### Small Explanation:

Feel Free to Skip. it’s optional. we will loop through the given array and we will check with the first value multiplication. If the array’s value is less than or equal to first value then array’s value will be the closest value.

If your question why need to multiply we can directly compare with our array’s value. but it will give you a negative output. That’s why need to multiply to compare then u will get the positive output.

##### Code Sample:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.practicehouse; import java.util.Arrays; /** * * @author marifurr */ public class ClosestToZero { /** * @param args the command line arguments */ public static void main(String[] args) { int[] testingArray = {4,7,9,2,-2}; int result = getClosestToZero(testingArray); System.out.println("The Closest Number To Zero in this Array is : " + result); } public static int getClosestToZero(int[] a) { int currentValue = 0; int closestVal = a[0]; Arrays.sort(a); for (int index = 0; index < a.length; index++) { currentValue = a[index] * a[index]; if (currentValue <= (closestVal * closestVal)) { closestVal = a[index]; } } return closestVal; } } |

#### Sample Output:

1 2 |
The Closest Number To Zero in this Array is : 2 BUILD SUCCESSFUL (total time: 0 seconds) |

Thanks for choosing us from your google search. We appreciate your intention. If you want to cover us some more complex interview questions related to Java, Spring, Hibernate, and SQL. Please let us know in the comment section. we will solve it for you.

Md Arifur Rahman, Nickname is Alif.

## Leave a Reply