Assigning null value to var variable

In this post under Java language, I will show with example how to assign null value to var variable.

Assigning a null value to a non-var variable is simple as shown below

	String message = "Hello World";
	.
	.
	.
	.
	message = null;

But assigning null value to var variable is different.

We need to cast the null value to the datatype inferred by the var variable.

Below is an example

	var message = "Hello World";
	.
	.
	.
	.
	message = (String) null;

In the above code, we first declare a var variable named “message” and initialize it to “Hello World”. Compiler will infer “message” of datatype String because a string value is assigned to the variable.

After few lines of code we try to assign null value to the var variable. So here we need to cast the null value to String datatype and assign it to var variable “message”.

Below is the complete code for your reference

Main class

package core.language;
public class LVTIExample3 {
public static void main(String[] args) {
var message = (String) null;
message = "Hello World";
System.out.println(message);
}
}

In this way we can assign null values to var variable.

Leave a Reply