Once a friend of mine asked me why is it so inconsistent that the index of first element of Java array is 0 while the first index of
java.sql.PreparedStatement's setters is 1. For example, see below code:
char[] alphabet = new char[26];
alphabet[0] = 'a'; // assign the character 'a' to array alphabet
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES
SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 1800.00); // assign 1800.00 to the first placeholder '?'
pstmt.setInt(2, 110592);Actually the answer is pretty simple, which I just found out. It's all about the purpose of the design. As we know, every element in an array has the same size, so, it is convenient to consider the index of the first element of the array to be zero (just as in C and Java). Have zero be the index of the first element, the compiler can simply calculate the memory address of the element using this formula:
element address = array base address + (index X element size)Although it is possible to use other values for the first index, it complicates the address computation. Consider following formula if we use 1 as the first index:
element address = array base address + ((index - 1) X element size)Obviously, less CPU instructions will be executed if the index 0 of first element is used. In contrast,
java.sql.PreparedStatement need not worry about this performance issue, the parameter setter methods are designed for human and they will be no different with using 1 or 0 to be the index of first parameter in terms of performance.