I came across this Java program and its behavior is unpredictable. The following program calculates 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 that the size of the set should be 8, which is the size of the array. But if you run this program, it will print 14. What is happening? Any ideas?
Thanks 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 put an integer literal with zeros.
source share