search
HomeJavajavaTutorialJava Type Inference

Type inference in java is a compiler process that automatically infers unspecified data types parameter from the contextual information. Consider an example where we want to create an object of type generic class. So to create this object we need to call the construct of a generic class with the specified type of parameters, like String, Float, Integer etc., which increase the length of code. To reduce this coding java provides the flexibility to learn the type parameter empty as long as the compiler judge or guess the type of parameter from the context. In addition to this java also provide the wildcards that allow the user to achieve the inheritance in a type parameter. Java 8 provides an improved version of type inference. In case of type, the inference is not used then the compiler generates an unchecked conversion warning.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

Syntax are as follow:

Generic_class  obj = new Generic_class ( );
Where -
Generic_class – Generic_class  is an  user create generic class.
<type_parameter> - type_parameter is a type parameter, which represented by agular brakets(), that can have one or more type of parameter separated by commas.
Obj – obj is the object of the generic class.
 −  (diamond) represents the type inference.</type_parameter>

Examples to Implement Java Type Inference

Next, we write the java code to understand this more clearly with the following example where we create a generic class to accept the pair of values by using the generic class constructor and create the objects of the generic class for different pair of data types and then use the type inference for the type parameters, as below –

Example #1

Code:

package p1;
class Pair <x y>
{
private x first;
private y second;
public Pair(x a, y b)
{
first=a;
second=b;
}
public x getFirst() {
return first;
}
public y getSecond() {
return second;
}
}
public class Demo
{
public static void main( String[] arg)
{
// unchecked conversion warning
Pair <integer string> ob1 = new Pair<integer string>(25, "Test1");
System.out.println("Integer value is : "+ob1.getFirst());
System.out.println("String valueis : "+ob1.getSecond());
System.out.println( );
// unchecked conversion warning
Pair <string integer> ob2 = new Pair<string integer>("Test2", 30);
System.out.println("String valueis : "+ob2.getFirst());
System.out.println("Integer is : "+ob2.getSecond());
System.out.println( );
// type inference,  left it blank, compiler will infer type
Pair <string integer> ob3 = new Pair<string integer>("Test3", 30);
System.out.println("Integer valueis : "+ob3.getFirst());
System.out.println("Integer value is : "+ob3.getSecond());
System.out.println( );
// type inference,  left it blank, compiler will infer type
Pair <integer integer> ob4 = new Pair(35, 40);
System.out.println("Integer value is : "+ob4.getFirst());
System.out.println("Integer value is : "+ob4.getSecond());
System.out.println( );
}
}</integer></string></string></string></string></integer></integer></x>

Output:

Java Type Inference

Explanation: As in the above code, the generic class Pair can two different data types in the class as x and y. Here, the first two objects creating by mentioning integer and /or String type explicitly at both sides, which are the earlier versions of Java. And in the last two objects creating examples the types are mentioning at one side(we can be left second side as blank), which was introduced in Java 7. And later introduce to call a specified method without explicitly mentioning of type of arguments in java 8, which we will see in the next example.

Example #2

Next, we write the java code to understand the new type inference where we create a generic class to accept the different type of message by using the generic class of setter method and create the objects of the generic class for the different message of different data types and then use the type inference for the type parameters, as below:

Code:

package demo;
class myGeneric 
{
private x msg;
public x getMsg() {
return msg;
}
public void setMsg(x msg) {
this.msg = msg;
}
public String genInf1(myGeneric <string> m){
m.setMsg( "This is a Hello Message." );
return m.msg;
}
public Integer genInf2(myGeneric <integer> m){
m.setMsg( 100 );;
return m.msg;
}
}
public class Demo {
public static void main(String[] args) {
// Before java 7 an old approach to create generic class object
myGeneric <string> msg1 = new myGeneric <string>();
msg1.setMsg( "This is a first Message.");
System.out.println(msg1.getMsg());
// type inference
myGeneric <integer> msg2 = new myGeneric ();
msg2.setMsg(20);
System.out.println(msg2.getMsg());
// New type inference
System.out.println(msg1.genInf1( new myGeneric() ));
System.out.println(msg1.genInf2( new myGeneric() ));
System.out.println(msg2.genInf1( new myGeneric() ));
System.out.println(msg2.genInf2( new myGeneric() ));
}
}</integer></string></string></integer></string>

Output:

Java Type Inference

Explanation: As in the above code, calling a specific(genInf1() and genInf2()) methods without explicitly mentioning of type of arguments which are the example of new type inference introduce in java 8.

Example #3

Next, we write the code to understand the new type inference where we create a list of the message by using the List generic class and create the objects of the list generic class for the different message of different data types and then use the type inference and new type inference for the type parameters, as below:

Code:

package demo;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main( String[] arg) {
// Before Java 7 to create a list
List <string> msg1 = new ArrayList <string>();
msg1.add("This is a first Message.");
getMsg(msg1);
// Java 7 type inference
List<string> msg2 = new ArrayList();
msg2.add("This is a second Message.");
getMsg(msg2);
// as list is generic class so add integer
List<integer> msg3 = new ArrayList();
msg3.add(100);
getMsg1(msg3);
// Java 8 Compiler type infers type of ArrayList
getMsg(new ArrayList());
}
public static void getMsg(List <string> m){
if(!m.isEmpty()){
m.forEach(System.out::println);
}else System.out.println("No Message.");
}
public static void getMsg1(List <integer> m){
if(!m.isEmpty()){
m.forEach(System.out::println);
}else System.out.println("No Message.");
}
}</integer></string></integer></string></string></string>

Output:

Java Type Inference

Conclusion

Type inference is used to create an object of type generic class and if we want compiler automatically to infer unspecified data types parameter from the context pass.

The above is the detailed content of Java Type Inference. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor