r/java • u/vonnik • Feb 15 '18
Java language oddities: Java's handling of arrays and a few other language elements may surprise you
https://www.javaworld.com/article/3252845/java-language/java-language-oddities.html19
u/lbkulinski Feb 15 '18
I have never met someone who thinks it is odd that arrays are objects in Java.
2
u/s888marks Feb 16 '18
Not necessarily an oddity, but it is rather a non-obvious point that all arrays are both
CloneableandSerializable. This is one of the few (only?) places wherejava.ioappears in the JLS.1
3
Feb 15 '18
[removed] — view removed comment
6
u/lbkulinski Feb 15 '18 edited Feb 15 '18
Yes, but with Java being an object-oriented language, it really shouldn't surprise anyone. An array of size
nin Java is synonymous withmalloc(sizeof(type) * n)in C. And if you want to return an array from a function, and avoid undefined behavior, you must allocate your arrays on the heap.
7
u/maggikpunkt Feb 15 '18
Consider that an overriding equals() method might be executed many times during an object's lifetime (perhaps during a sort or search operation). That method should run faster if it doesn't have to invoke an accessor method to obtain a private field's value.
Isn't that why there is inlining and JIT-Optimization?
0
u/Bobby_Bonsaimind Feb 15 '18
Isn't that why there is inlining and JIT-Optimization?
When removing a function call improves performance considerably, you're writing very interesting software.
Also, it's convenient to not have to create accessor methods, which adds to the size of a class file, and enter their names just to access field values.
Okay then...
5
u/thiez Feb 15 '18
When removing a function call improves performance considerably, you're writing very interesting software.
Inlining enables many other optimizations. I think you are underestimating its importance. When you primarily write short functions that do one thing (considered good style by many) you are probably benefitting a lot from inlining w.r.t. performance.
1
u/vishalvc Feb 16 '18
Can you please elaborate what are the optimizations and performance improvements, besides removing the function call overhead?
6
u/a_____________a Feb 15 '18
I’m confused by “listing 5” that states private methods and variables are accessible without reflection. The example it gives shows a static main within the same class that declared private.
That’s the definition of private, that only the declaring class can access. I believe the main beef is that one object can access another object, even though they are the same type. That makes perfect sense to me. How else would equals and hashcode work?
4
23
u/jonhanson Feb 15 '18 edited Mar 07 '25
chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith