‘?’ is used as wild card character in java generics concept . Before going to learn use of the wild card character, let’s see the sample below.

import java.util.ArrayList;
import java.util.List;
public class Sample {
    public int size(List<String> arrayList) {
        return arrayList.size();
    }
    public static void main(String as[])
    {
         List<String> names = new ArrayList<String> ();
         names.add("sree");
         names.add("krish");
         System.out.println(new Sample().size(names));
    }
}



See the above example, size() method in the sample class allows only String type list as a parameter . If we pass any other type list , compiler error will be given . Below code causes compiler error.

     List<Integer> age = new ArrayList<Integer> ();
     age.add(26);
     age.add(25);
     System.out.println(new Sample().size(age));

     // above code causes compiler error.
     // because size() allows String type ArrayList only


Now my question is how to force the size() method to allow any type List as parameter . The answer is , using wild card character '?' . For better understanding, see the below example .
import java.util.ArrayList;
import java.util.List;
public class Sample {
    public int size(List<?> arrayList) {
        return arrayList.size();
    }
    public static void main(String as[])
    {
         List<String> names = new ArrayList<String> ();
         names.add("sree");
         names.add("krish");
         System.out.println(new Sample().size(names));
         List<Integer> age = new ArrayList<Integer> ();
           age.add(26);
           System.out.println(new Sample().size(age));
    }
}

// No compiler error will be given. 
// Size() method accepts any type of list Now.

Here ‘?’ means compiler don’t know the type. Again i have a question what is the difference between below two methods . Below both methods allows any list type as parameter, but what is the difference ? . public int size(List<?> arrayList) {
—–
}
public int size(List arrayList) {
—–
}

First method with wild card character gives type safety.Because , compiler don’t know the list type , it won’t allow to add elements to list with in the method . But second method allows to add any elements with in the method . So , we don’t get type safety . See the below example.

import java.util.ArrayList;
import java.util.List;

public class Sample {
    public void add(List<?> arrayList) {
        arrayList.add("raj"); // causes compiler error.
        arrayList.add(null); // fine compilation . 
                  // null only allowed to add here.
    }

    public void add1(List arrayList) {
        arrayList.add("sree"); // fine compilation. we can add any type
    }

    public static void main(String as[]) {
        List<String> names = new ArrayList<String>();
        names.add("sree");
        names.add("krish");
        new Sample().add(names);
    }
}