I came across this Java program and its behaving in unexpected way. The following program computes the differences between pairs of elements in an int array.
import java.util.*;
public class SetTest
{
public static void main(String[] args)
{
int vals[] = {786,678,567,456,
345,234,123,012};
Set<Integer> diffs = new HashSet<Integer>();
for(int i=0; i < vals.length ; i++)
for(int j = i; j < vals.length; j++)
diffs.add(vals[i] - vals[j]);
System.out.print(diffs.size());
}
}
If we analyze it seems set size should be 8 which is the size of the array. But if you ran this program it prints 14. What's going on? Any idea?
Thank you in advance.
Answer: This strange behavior happens because 012 in the array becomes octal if we change it to 12 then it prints 8 as expected.
Lesson: Never pad an integer literal with zeros.