Java #5 - Variables

Topics

  1. Variable
  2. Types of variables
  3. Type Conversion and Casting
  4. Type inference - var

Variable

A variable is a name for a piece of memory that stores data and it is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and lifetime.

Syntax

type identifier [ = value][, identifier [= value] …];
  • type is one of Java’s primitive data types or the name of a class or interface.

  • An identifier is the name of a variable, method, class, interface, or package. Luckily, the rules for variables' identifiers apply to all the other types you are free to name.

There are only four rules to remember for legal identifiers:

  1. Identifiers must begin with a letter, a $ symbol, or a _ symbol.
  2. Identifiers can include numbers but not start with them.
  3. Since Java 9, a single underscore _ is not allowed as an identifier.
  4. You cannot use the same name as a Java reserved word. A reserved word is special word that Java has held aside so that you are not allowed to use it.

Style: camelCase

Java has conventions so that code is readable and consistent. This consistency includes camel case, often written as camelCase for emphasis. In camelCase, the first letter of each word is capitalized.

Below conventions are used in Java for identifier names:

  1. Method and variable names are written in camelCase with the first letter being lowercase.
  2. Class and interface names are written in camelCase with the first letter being uppercase. Also, don’t start any class name with $, as the compiler uses this symbol for some files.

Types of variable

Below are the types of variables -

  1. Local variable - A local variable is a variable defined within a constructor, method, or initializer block. Local variables do not have a default value and must be initialized before use. Furthermore, the compiler will report an error if you try to read an uninitialized value. Here is another important point to remember: variables are created when their scope is entered, and destroyed when their scope is left. This means that a variable will not hold its value once it has gone out of scope. Therefore, variables declared within a method will not hold their values between calls to that method. Also, a variable declared within a block will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope. Although blocks can be nested, you cannot declare a variable to have the same name as one in an outer scope.
  2. Passing Constructor and Method Parameters - Variables passed to a constructor or method are called constructor parameters or method parameters, respectively. These parameters are local variables that have been pre-initialized. In other words, they are like local variables that have been initialized before the method is called, by the caller.
  3. Defining Instance and Class Variables - Variables that are not local variables are defined either as instance variables or as class variables. An instance variable often called a field, is a value defined within a specific instance of an object. A class variable is one that is specified on the class level and shared among all instances of the class. It can even be publicly accessible to classes outside the class without requiring an instance to use. Instance and class variables do not require you to initialize them. As soon as you declare these variables, they are given a default value.

Type Conversion and Casting

It is fairly common to assign a value of one type to a variable of another type. If the two types are compatible, then Java will perform the conversion automatically. For example, it is always possible to assign an int value to a long variable. However, not all types are compatible, and thus, not all type conversions are implicitly allowed. For instance, there is no automatic conversion defined from double to byte. Fortunately, it is still possible to obtain a conversion between incompatible types. To do so, you must use a cast, which performs an explicit conversion between incompatible types. Let’s look at both automatic type conversions and casting.

Java’s Automatic Conversions

When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met:

  • The two types are compatible
  • The destination type is larger than the source type.

For widening conversions, the numeric types, including integer and floating-point types, are compatible with each other. However, there are no automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with each other.

As mentioned earlier, Java also performs an automatic type conversion when storing a literal integer constant into variables of type byte, short, long, or char.

Casting Incompatible Types

Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if you want to assign an int value to a byte variable? This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing conversion since you are explicitly making the value narrower so that it will fit into the target type.

To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type of conversion. It has this general form: Syntax (target-type) value

If the integer’s value is larger than the range of a byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range.

int a;
byte b;
b = (byte) a;

A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation. If the size of the whole number component is too large to fit into the target integer type, then that value will be reduced modulo the target type’s range.

Automatic Type Promotion in Expressions

Java automatically promotes each byte, short, or char operand to int when evaluating an expression

The Type Promotion Rules

Java defines several types of promotion rules that apply to expressions. They are as follows: First, all byte, short, and char values are promoted to int, as just described. Second, if one operand is long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands are double, the result is double.

Type inference - var

var is the new keyword added from Java 10 which has the formal name "local variable type inference". It is only applicable for local variables. Type inference means the compiler will infer the type of a variable at the time of declaration based on the value assigned to a variable.

Below are rules applicable for var:

  1. A var is used as a local variable in a constructor, method, or initializer block.
  2. A var cannot be used in constructor parameters, method parameters, instance variables, or class variables.
  3. A var is always initialized on the same line (or statement) where it is declared.
  4. The value of a var can change, but the type cannot.
  5. A var cannot be initialized with a null value without a type.
  6. A var is not permitted in a multiple-variable declaration.
  7. A var is a reserved type name but not a reserved word, meaning it can be used as an identifier except as a class, interface, or enum name.

Did you find this article valuable?

Support SUBODH SINGH by becoming a sponsor. Any amount is appreciated!