Why Java method has length like method().length?

77 Views Asked by At

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();
    }
}
1

There are 1 best solutions below

0
Mark Rotteveel On BEST ANSWER

The method doesn't have a length property. The method you're calling returns StackTraceElement[], which is an array, and arrays have a length property. In other words, you call the method method1(), it returns an array, and then length is called on that array.

It is the same as if your code was:

StackTraceElement[] elements = method1();
int stackTraceLength = elements.length;

But just without the intermediate elements variable (also known as chaining).

The fact you can't call main().length has two reasons.

  1. Your code doesn't have a main() method, it has a main(String[]) method, so there is no method to be called
  2. Assuming you meant something like main(new String[0]).length, that won't work because main(String[]) has the return type void, which means nothing is returned, so there is no return value to call length on.