I don't understand how the method can have length? method1().lenght. Following the same logic we can write main().length
public class Solution {
public static void main(String[] args) {
int stackTraceLength = method1().length;
System.out.print(stackTraceLength);
System.out.print(main().length);
}
public static StackTraceElement[] method1() {
return Thread.currentThread().getStackTrace();
}
}
The method doesn't have a length property. The method you're calling returns
StackTraceElement[], which is an array, and arrays have alengthproperty. In other words, you call the methodmethod1(), it returns an array, and thenlengthis called on that array.It is the same as if your code was:
But just without the intermediate
elementsvariable (also known as chaining).The fact you can't call
main().lengthhas two reasons.main()method, it has amain(String[])method, so there is no method to be calledmain(new String[0]).length, that won't work becausemain(String[])has the return typevoid, which means nothing is returned, so there is no return value to calllengthon.