I have errors when I run program(1). But when I used program(2), writing 0 after a, it run and produced the correct output. Writing 0, is just my guess and somehow it worked. Why is that?
Program (1):
public static void main(String[] args) {
System.out.println(a);
}
private static int a(int len) {
String s = "What";
len = s.length();
return (len);
}
}
Program (2):
public static void main(String[] args) {
System.out.println(a(0));
}
private static int a(int len) {
String s = "What";
len = s.length();
return (len);
}
}
You wrote the function in such a way that it requires a parameter. To call a function that requires a parameter, you have to supply one. That’s why the second program worked–you gave the function a a parameter of 0.
To make the first program work, then, you have two options. The first is what you did–supply the required parameter for the function. The second is to modify the function declaration so it does not require a parameter, changing
to