© Mikael Olsson 2022
M. OlssonJava 17 Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-7371-5_3

3. Variables

Mikael Olsson1  
(1)
Hammarland, Länsi-Suomi, Finland
 

Variables are used for storing data in memory during program execution.

Data Types

Depending on what data you need to store, there are several kinds of data types. Java has eight types built into the language, called primitives . The integer (whole number) types are byte, short, int, and long. The float and double types represent floating-point numbers (real numbers). The char type holds a Unicode character, and the boolean type contains either a true or false value. Except for these primitive types, every other type in Java is represented by a class, an interface, or an array.

Data Type

Size (Bits)

Description

byte

short

int

long

8

16

32

64

Signed integer

float

double

32

64

Floating-point number

char

16

Unicode character

boolean

1

Boolean value

Declaring Variables

To declare (create) a variable, you start with the data type you want it to hold followed by a variable name. The name can be anything you want, but it’s a good idea to give your variables names that are closely related to the values they will hold. The standard naming convention for variables is that the first word should be lowercase and any subsequent words initially capitalized.
int myInt;

Assigning Variables

To give the variable a value, you use the assignment operator (=) followed by the value. When a variable is initialized (assigned a value), it then becomes defined (declared and assigned).
myInt = 10;
The declaration and assignment can be combined into a single statement:
int myInt = 10;
If you need multiple variables of the same type, there is a shorthand way of declaring or defining them using the comma operator (,):
int myInt = 10, myInt2 = 20, myInt3;

Using Variables

Once a variable has been defined, you can use it by simply referencing the variable’s name—for example, to print it:
System.out.print(myInt);

Integer Types

As shown earlier, there are four signed integer types you can use, depending on how large a number you need the variable to hold:
byte  myInt8  = 2;  // -128   to +127
short myInt16 = 1;  // -32768 to +32767
int   myInt32 = 0;  // -2^31  to +2^31-1
long  myInt64 = -1; // -2^63  to +2^63-1
In addition to standard decimal notation, integers can also be assigned by using octal or hexadecimal notation. As of Java 7, a binary notation is also available.
int myHex = 0xF;  // hexadecimal (base 16)
int myOct = 07;   // octal (base 8)
int myBin = 0b10; // binary (base 2)
Digits in a number can be separated by an underscore (_). This feature was introduced in Java 7 and is provided only to improve readability.
int bigNumber = 10_000_000;

Floating-Point Types

The floating-point types can store integers as well as floats. They can be assigned with either decimal or exponential notation.
double myDouble = 3.14;
double myDouble2 = 3e2; // 3*10^2 = 300
Note that constant floating-point numbers in Java are always kept internally as doubles. Therefore, if you try to assign a double to a float, you’ll get an error because a double has a higher precision than a float. To assign it correctly, you can append an F character to the constant, which says that the number is in fact a float.
float myFloat = 3.14;  // error
float myFloat = 3.14F; // ok
A more common and useful way to do that is by using an explicit cast. An explicit cast is performed by placing the desired data type in parentheses before the variable or constant that is to be converted. This will convert the value to the specified type—in this case, float—before the assignment occurs.
float myFloat = (float)3.14;

Char Type

The char data type can contain a single Unicode character, delimited by single quotes:
char myChar = 'A';
Chars can also be assigned by using a special hexadecimal notation that gives access to all Unicode characters:
char myChar = 'u0000'; // u0000 to uFFFF

Boolean Type

The boolean type can store a Boolean value, which is a value that can only be either true or false. These values are specified with the true and false keywords.
boolean myBool = false;

Variable Scope

The scope of a variable refers to the code block within which it’s possible to use that variable without qualification. For example, a local variable is a variable declared within a method. Such a variable will only be available within the method’s code block, after it’s been declared. Once the scope (code block) of the method ends, the local variable will be destroyed.
public static void main(String[] args)
{
  int localVar; // local variable
}

In addition to local variables, Java has field- and parameter-type variables, which later chapters will cover. But Java doesn’t have global variables, as, for example, C++ does.

Anonymous Block

You can restrict the scope of local variables using an anonymous (unnamed) code block. This construct is seldom used, because if a method is large enough to warrant the use of an anonymous block, a better choice is often to break up the code into separate methods.
public static void main(String[] args)
{
  // Anonymous code block
  {
    int localVar = 10;
  }
  // localVar is unavailable from here
}

Type Inference

Beginning with Java 10, local variables can be declared with var to have the compiler automatically determine the type of the variable based on its assignment. The following two declarations are therefore equivalent:
var i = 5; // Implicit type
int i = 5; // Explicit type
When to use var comes down to preference. In cases when the type of the variable is obvious from the assignment, use of var may be preferable to shorten the declaration and improve readability. The benefit becomes more apparent when using a non-primitive type as seen in this example.
// No type inference
java.util.ArrayList a = new java.util.ArrayList();
// With type inference
var a = new java.util.ArrayList();

Keep in mind that var can only be used when a local variable is both declared and initialized at the same time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.71.237