This Blog is Under Construction

Wednesday, January 11, 2017

Variable Length Argument

Variable length argument কে সংক্ষেপে varargs বলে। JDK1.5 থেকে এই feature টি চলে আসছে। যাই হোক fun 
নামে একটি function কল্পনা করি, যার চারটি arguments.

fun(int, String, String, String)
তাহলে আমরা জানি same function নামে same argument যুক্ত এই রকম একটি function থাকতে হবে।
তানাহলে fun function টিকে call করতে পারব না। যেমন--


public class TestClass{
     public static void main(String parameters[]){
             int x;
             String a, b, c; 
             fun(x, a, b, c);
     }

     private static void fun(int a, String b, String c, String d){
              //do the stuff
     }

}
এখন লক্ষ করুন String type যুক্ত argument যদি 100 টা হয় তাহলে কি আপনি ১০০ টি argument লিখবেন? না
লেখার দিন শেষ। আমরা এর জন্য use করব varargs. এটি লেখার নিয়ম হল type লিখে পরপর তিনটি ডট(...) লিখে
একটি local variable দিলেই কাজ খতম। নিচের কোডটি লক্ষ করুন।


public class TestClass{
     public static void main(String parameters[]){
            int x;
            String a, b, c; 
            fun(x, a, b, c);
     }

     private static void fun(int a, String... variables){
             //do the stuff
      }

}

No comments:

Post a Comment