Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 113

Type Inference of var

Оглавление

Now that you understand the local variable part, it is time to go on to what type inference means. The good news is that this also means what it sounds like. When you type var, you are instructing the compiler to determine the type for you. The compiler looks at the code on the line of the declaration and uses it to infer the type. Take a look at this example:

7: public void reassignment() { 8: var number = 7; 9: number = 4; 10: number = "five"; // DOES NOT COMPILE 11: }

On line 8, the compiler determines that we want an int variable. On line 9, we have no trouble assigning a different int to it. On line 10, Java has a problem. We've asked it to assign a String to an int variable. This is not allowed. It is equivalent to typing this:

int number = "five";

If you know a language like JavaScript, you might be expecting var to mean a variable that can take on any type at runtime. In Java, var is still a specific type defined at compile time. It does not change type at runtime.

For simplicity when discussing var, we are going to assume a variable declaration statement is completed in a single line. You could insert a line break between the variable name and its initialization value, as in the following example:

7: public void breakingDeclaration() { 8: var silly 9: = 1; 10: }

This example is valid and does compile, but we consider the declaration and initialization of silly to be happening on the same line.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх