πŸ“Š JAVA
Q. Choose all the lines which if inserted independently instead of "//insert code here" will allow the following code to compile:
Code:
public class Test{   
        public static void main(String args[]){
	        add(); 
		add(1);
		add(1, 2); 
	}

	// insert code here
}
  • (A) void add(Integer... args){}
  • (B) static void add(int... args, int y){}
  • (C) static void add(int...args){}
  • (D) static void add(int[]... args){}
πŸ’¬ Discuss
βœ… Correct Answer: (C) static void add(int...args){}

Explanation: var-args = variable number of arguments = 0 or many

void add(Integer... args){} is correct IF made "static" as it's called from a static context: main().
Var-args can be of both object(eg Integer) and primitive(eg int) types.

static void add(int... args, int y){} is correct IF its parameters' order is reversed.
If a method has both var-arg(0 or MAX 1) + non-var-args(0 or more) parameters then the var-arg parameter MUST come LAST!

static void add(int args...){} : "..." must come after the type of the var-arg parameter, not after its name

static void add(int[]... args){} : for this to be a correct declaration then add() should have been called something like this: "add(arr);" or "add(arr, arr);" where "arr" could be defined as "int[] arr = new int[5];"

static void add(int...args){} is a valid way to define var-args (there is no need to have any space between "..." and the type and name of the var-arg param)

Explanation by: Jatin Dubey
var-args = variable number of arguments = 0 or many

void add(Integer... args){} is correct IF made "static" as it's called from a static context: main().
Var-args can be of both object(eg Integer) and primitive(eg int) types.

static void add(int... args, int y){} is correct IF its parameters' order is reversed.
If a method has both var-arg(0 or MAX 1) + non-var-args(0 or more) parameters then the var-arg parameter MUST come LAST!

static void add(int args...){} : "..." must come after the type of the var-arg parameter, not after its name

static void add(int[]... args){} : for this to be a correct declaration then add() should have been called something like this: "add(arr);" or "add(arr, arr);" where "arr" could be defined as "int[] arr = new int[5];"

static void add(int...args){} is a valid way to define var-args (there is no need to have any space between "..." and the type and name of the var-arg param)

πŸ’¬ Discussion


πŸ“Š Question Analytics

πŸ‘οΈ
295
Total Visits
πŸ“½οΈ
3 y ago
Published
πŸŽ–οΈ
Jatin Dubey
Publisher
πŸ“ˆ
82%
Success Rate