Search code examples
javaobjectvectortostringgetelementbyid

Java / Statements containing multiple '.' operators


In Java, consider the following piece of code:

Vector v = new Vector();
for(int i = 1; i <= 10; i++)
{
    v.addElement(Integer.toString(i));
}
System.out.println(v.elementAt(9).toString());

Are Java statements like v.elementAt(9).toString() containing multiple '.' operators perfectly fine enough at all or do they cause any given type of conflict during some given period of time after all?

So far, I have only always kept them as safe enough in parenthesis, by making use of putting away off parenthesis around individual statements, so as not to create with any given type of conflict at all, after all.

(v.elementAt(9)).toString().

So far, I have never created with any given type of ambiguous statements like that during all of my own more than over a decade of programming and coding experience.

v.elementAt(9).toString().


Solution

  • Are Java statements like v.elementAt(i).toString() containing multiple '.' perfectly fine enough at all or do they cause any given type of conflict during some given period of time after all?

    They are perfectly fine, with some caveats. If v.elementAt(i) is null, then calling v.elementAt(i).toString() will throw a NullPointerException. If you select i as some value that is either negative or larger than the Vector, I suspect an ArrayIndexOutOfBoundsException will be thrown as well. You can think of this syntax as the composition of functions (left-to-right), which is opposite how it is in mathematics.

    In your specific example, this syntax is logically equivalent:

    (v.elementAt(i)).toString()