0

Why does a main() function in java doesn't throw a 'actual and formal parameters mismatch error' even if the program doesn't involve getting input from the command line.This is a sample program where the near() function has same number of actual and formal parameters and compiles without any error,whereas the far() method throws a parameter mismatch error since I haven't given any parameters while calling it.

import java.util.Scanner;
import java.io.*;

class Prime
{
 void near(int x,int y)
 { 
  System.out.println(x+y);
 }

 void far(int a,int b)
 {
  System.out.println(a+b);
 }

 public static void main(String args[])
 {
  Prime n=new Prime();
  n.near(5,4);
  n.far();
 }
}


C:\Users\hcl\Desktop>javac Prime.java

C:\Users\hcl\Desktop>javac Prime.java
Prime.java:20: error: method far in class Prime cannot be applied to given types
;
  n.far();
   ^
  required: int,int
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

2 Answers2

3

First, you are confusing runtime and compile-time errors.

The error you have shown is not "thrown". It is a compilation error, indicating that you have a faulty method invocation in your code.

But there is usually no invocation of main in any Java code. main is the starting point for the program, and the invocation of it is done by the JVM itself at runtime. When you do not have a method invocation in your source, you will not get compile errors that relate to that invocation.

Second, when the JVM invokes that method, it will always pass a string array to it. If no arguments were present on the command line, the string array will be empty. You can write an example main that prints the length of the array and see for yourself.

Finally, if you don't have a main method that's specified exactly according to spec (public static void with a single parameter of type String[]), the JVM will issue an error when you try to invoke your program. So if you try to write your main with two parameters or with a parameter of type int[] or something like that, you will get an error. It won't be a compile error, as it is perfectly legal to have such a method in your program. But it will be a runtime error - as the JVM cannot find the entry point to your program.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
1

The main method is getting an empty String[] as input. Because that's the input: nothing.

Your function far needs input, so you have to give it input.

See this post by jjnguy.

The arguments can never be null. They just won't exist. -jjnguy

For example, if you run without command line arguments, you will reach this comment:

public static void main(String[] args){
    if(args.length == 0){
        //there is no command line input, but args still exists
    }
}
Community
  • 1
  • 1
Arc676
  • 4,445
  • 3
  • 28
  • 44