How to Use Basic Generics Syntax in Java

You can create a class in Java that defines one or more placeholders for data type. The placeholders are known as generics because the class is not determined until compile time. Generics are notated by angle brackets (< and >). For example, we might wish to create a class that contains a method that accepts an argument of any data type and displays the value of the argument. Because we don't know the data type when we are developing the class, we must use a generic for the method argument data type. To apply basic generics syntax in Java, follow these four steps.

  1. Open your text editor and type in the following Java statements:
    Java Source for Basic Generics
    The class that contains the generic syntax is named GenericsDisplay. Note the generic parameter T after the class name on line 10. We could use any other letter or a longer name if we wished, but using the one-letter parameter name "T" (as in "Type") is considered best practice, as this letter is used in the Core API. Notice that the data type of the argument in the display method is T. At compile time, the generic argument type will be replaced with the data type of the parameter that is passed to the method. In the output of this method the value of the argument is displayed along with its data type. In this way, we can verify at run time that the correct data type was communicated to the class using the generic parameter. Two objects are instantiated in the main method, each using a different class name as the value for the generic parameter. Now, all occurrences of T in the GenericsDisplay class with be replaced with the class provided when the object is instantiated (e.g., String). The main method calls the display method for each object.
  2. Save your file as
  3. Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.
    Compile Source for Basic Generics
  4. Type in the command to run your program and hit Enter. Notice in the output that a String variable and a Date variable were each successfully passed to the generic class method.
    Run for Basic Generics

Related Video

Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.