×

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as to specify the type of an argument, field, or local variable, or even as a return type on occasion. Contrary to arrays, a generic type's various instantiations are not consistent with one another or not even explicitly. If do? Then it is utilized as a genuine type parameter, the wildcard may help to mitigate this mismatch.

  • Java's wildcards are essentially the question marks that are used in generic programming to denote unknown types. Java Wildcard is frequently used as a return type as well as a kind of parameter, local variable, or field.
  • Multiple new structures of a generic type are incompatible with one another, not even explicitly, unlike arrays. By adding the wildcard character "?" as a genuine type parameter, we can get rid of the issue
  • The question mark (?) that you employ in Java Generics is what is known as a wildcard. The Java Wildcard can be used as a field, local variable, argument, or return type. However, we are unable to use wildcards whenever the generic class is created or when the generic function is used.
  • The use of the wildcard helps eliminate incompatibility between various instances of a generic type. Using wildcards as a true-type argument eliminates this mismatch.

In and out parameters are the two different types of parameters we pass to a method. As follows:

  1. in variable

    The Java program receives the actual data from the variable called in. There is a method called myMethod(source, destination). The source functions as an in-method variable in this technique.
  2. out variable
    The revised data is saved by the Java application in a variable called out. There is a method called myMethod(source, destination). Destination serves as the method's output variable in this method.

Types of Java Wildcards

  1. Lower Bounded Wildcard
  2. Upper Bounded Wildcards
  3. UnBoubded Wildcards

So, to sum up, every wildcard are used in the following three ways:

  • Wildcard upper bound:? extends Type.
  • Wildcard with a lower bound: super Type.
  • Unbounded Wildcard:?

Lower Bounded Wildcard

To expand the scope of the kind of variable's use, we employ the Lower Bounded wildcards. For instance, creators can use the ListInteger> to add a list of integers to our method, but by doing so, we are restricted to using only the list of numbers.

In order to save the list of integers, we may also use the ListNumber> and ListObject>. Therefore, we employ the Lower Bounded wildcard. This may be used as a wildcard character, right? and place the lower bound after that, then a superkeyword.

Example program

import java.util.Arrays;
import java.util.List;
class WildcardDemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList(5, 6, 7, 8);
printOnlyIntegerClassorSuperClass(list1);
List<Number> list2 = Arrays.asList(5, 6, 7, 8);
printOnlyIntegerClassorSuperClass(list2);
}
public static void printOnlyIntegerClassorSuperClass(
List<? super Integer> list)
{
System.out.println(list);
}
}

Output

[5, 6, 7, 8]
[5, 6, 7, 8]

Upper Bounded Wildcards

The wildcard that loosens the constraint of the variable type is the Upper Bounded wildcard. In other words, we may use this kind of wildcard if we wish to loosen the constraint on the kind of variables in the procedure.

For instance, the method sum, which computes the sum of any type of variable, whether it is an int or a double variable type variable, uses the upper bound wildcard.

Example program

import java.util.Arrays;
import java.util.List;


class WildcardDemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList(5, 6, 7, 8);
System.out.println("Total sum is:" + sum(list1));
List<Double> list2 = Arrays.asList(5.1, 6.1, 7.1);
System.out.print("Total sum is:" + sum(list2));
}


private static double sum(List<? extends Number> list)
{
double sum = 0.0;
for (Number i : list) {
sum += i.doubleValue();
}


return sum;
}
}

Output

Total sum is: 26.0Total sum is:18.299999999999997

Unbounded Wildcards

When we want to indicate the kind of wildcard using the wildcard character?, we have used the Unbounded wildcards. This wildcard is typically used when the method's code makes use of Object functionality and when the method's code is independent of the parameter type.

import java.util.Arrays;
import java.util.List;
class unboundedwildcardemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList(2, 4, 6);
List<Double> list2 = Arrays.asList(2.1, 3.2, 4.3);
printlist(list1);
printlist(list2);
}
private static void printlist(List<?> list)
{
System.out.println(list);
}
}

Output

[2, 4, 6][2.1, 3.2, 4.3]

Java Wildcard Use Guidelines

The instructions for using each kind of variable in the following circumstances are provided below:

  • Upper bound wildcard: We use the 'extends' keyword with a wildcard if the variable is of the in type, i.e., it is an in a variable.
  • Lower bound wildcard: We utilize the super keyword along with a wildcard if the variable is of the out type, i.e., if it is an out variable.
  • Unbounded wildcard: When we can retrieve a variable via the Object class function, we should choose to use unbounded wildcards instead.
  • No wildcard: Wildcards are not necessary if the variable falls into both the in and out categories.

Conclusion

The wildcard in Java was examined in this article. When using generics in Java, we use wildcards. We looked at how to use them for our requirements. We are able to pass the exact parameter type with the aid of wildcards.

In Java, there are three different kinds of wildcards: Upper bounded, Lower bounded, and Unbounded wildcards.


Related Topics

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

String Coding Interview Questions in Java

What is String in Java?In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings...

5 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.