Javatpoint Logo
Javatpoint Logo

Wildcards in Java

In Java, the question mark (?) is considered or recognised as the wildcard. The main purpose of wildcard in Java is utilized for representing a type which is unknown.

Wildcards

In various scenarios or situations in Java, the wildcards could be utilized in the form of parameters, fields, local variables, or return types. Let's understand about types of wildcards in Java.

Types of Wildcards in Java

There are several types of wildcards in Java and let's discuss about it in detail.

1. Upper Bounded Wildcards

The Upper Bounded Wildcards could be majorly utilized in situations when the user wants to relax or simplify the restrictions that are imposed on a variable. For instance, a user desires to create a method that works with a List<Integer>, List<Double>, and List<Number>. The Java user could simply do the above-mentioned functionality with the help of upper bounded wildcard.

The declaration of an upper-bounded wildcard could be carried out with the help of the wildcard character '?', and that should be followed by extends keyword, and finally must be followed by the upper bound. The syntax for the upper-bounded wildcard is mentioned below:

Let's understand about upper-bounded wildcard in detail with the help of a Java example program.

Filename: UpperBoundedWildcard.java

Output:

Total Sum of the List is:10.0
Total Sum of the List is:15.299999999999999

2. Lower Bounded Wildcards

The major difference between upper-bounded wildcards and lower-bounded wildcards is that, in lower-bounded wildcards the usage of the wildcard character (?) is followed by the super keyword, which is also followed by its lower-bound. Let us understand about upper-bounded wildcard in detail with the help of a Java example program.

Filename: LowerBoundedWildcards.java

Output:

[1, 2, 3, 4]
[5, 6, 7, 8]

3. Unbounded Wildcard

The unbounded wildcard type is majorly declared or specified with the help of the wildcard character (?). The unbounded wildcards are utilized in situations when declaring or creating a method that needs to be employed by utilizing the functionality that is available in the Object class. Also, when the code is utilizing methods that are available in the generic class and which are not dependent on the parameter type. Let us understand about upper-bounded wildcard in detail with the help of a Java example program.

Filename: UnboundedWildcard.java

Output:

[1, 2, 3]
[4.4, 5.5, 6.6






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA