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

Inferring the Type with var

Оглавление

You have the option of using the keyword var instead of the type when declaring local variables under certain conditions. To use this feature, you just type var instead of the primitive or reference type. Here's an example:

public class Zoo { public void whatTypeAmI() { var name = "Hello"; var size = 7; } }

The formal name of this feature is local variable type inference. Let's take that apart. First comes local variable. This means just what it sounds like. You can only use this feature for local variables. The exam may try to trick you with code like this:

public class VarKeyword { var tricky = "Hello"; // DOES NOT COMPILE }

Wait a minute! We just learned the difference between instance and local variables. The variable tricky is an instance variable. Local variable type inference works with local variables and not instance variables.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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