12 June 2020

What is a variable in Java?


Welcome to another tutorial from our "How To Code In Java" tutorial series. In the last tutorial, you have learned how to write your very first Java program. In this tutorial, you'll be learning about what's a variable and the different types of it. The basic terminology used for the variable as well as the rules when naming a variable. Since this is a tutorial series on Java, I'll be using Java syntax to explain the topics covered in this tutorial. Other programming languages won't have many differences in their concept, so don't worry much about it. So, let's begin.


Things that we'll be covering:




What is a variable


As a general explanation, a variable is a container that lets us temporarily store data while the program is running. When storing the data, we need to give the variable a label (name) or more specifically an identifier, so that they can be referenced (looked back) or manipulated later on during the run-time (while the program is running) of a program. A variable can be either mutable (changeable) or immutable (unchangeable). 

When defining a variable, we need to specify which data type that the variable belongs to. Each data type prescribes and limits the form of data that could be stored in a variable. Data types also specify which relation, logical and mathematical operations that could be applied onto the variable without causing an error. 


There are several kinds of data types. But, they are mainly divided into two groups:

  1. Primitive data types
  2. Non-primitive data types

A primitive data type is predefined by the programming language. The size of the storage and type of data that could be stored is all specified. While it also has no additional method (functions) in it. They are used when a new variable is to be created. Variable is stored in the stack memory created during run-time.

While a non-primitive data type is created by programmers instead of predefined by the programming language. When a variable is defined with a non-primitive data type, the variable will be referenced to an object's memory location stored in the JVM's heap. While the variables that hold the reference to the object is located in the stack memory. 

A non-primitive variable is also called a reference data type or object reference variable. In Java, a non-primitive data type is simply called objects which are created during class instantiation. For a simple explanation on classes and objects, please read my last post where I explain how to write a basic Java program while explaining line-by-line what's going on.


Variable Naming Rules



Before we get into the primitive data type variables, lets first look at the rules for naming a variable:

  • The names can only contain letters, digits, underscores, and dollar signs.
  • It cannot begin with digits, you can only start with letters, underscores or dollar signs.
  • No whitespace is allowed.
  • Names are case sensitive in Java ("variable" and "Variable" are two different variables)
  • Reserved words are not allowed. In Java keywords like char or double cannot be used as names.

Example of valid variable:
  • number2
  • Upperlimit
  • _date
  • $Amount
  • _account3$ 

The naming is quite terrible but for the sake of understanding just bare with me. Below is a few examples of invalid variable names:

  1. 2apple
  2.  whitespace
  3. @add
  4. random space

Now let's see why do these variable are invalid:

  1. A variable cannot starts with a digits
  2. A variable can only consist of numbers, letters(both upper and lower case), underscores, and dollar signs.
  3. same as the previous variable
  4. A variable cannot contain whitespace. 

If you have doubt on any variable name that might be valid or not, feel free to ask in the comment section below.


Basic Variable Terminology


When we deal with variables operation, we used some terminology or terms to clearly specify what are we doing. Some basic terms are:

  • Identifier
  • Data type
  • declare
  • initialise
  • Assign
  • increment and decrement
  • scope of variable
  • Retrieve and use a value stored in a variable

Variable structure

Identifier


The identifier is the name of the variable

Data  type


When dealing with variable, you'll also need to know which data types for the variable so that you could store data correctly.

Declare


In programming language such as Java, every variable would need to be declared first before we can use them.

Initialise 


After declaring a variable, we can choose whether we want to give the variable to store data when it's created.

Assign


If the variable is not a constant (immutable), then we can always change the value of the variable by "assigning" new data to the variable using the equal sign (=).

Increment and decrement


In a programming language, if a variable is storing a number (decimal number or whole number), we can increase and decrease its value by 1 (one) using the increment (++) and decrement (--) operator. More info regarding this will be in the next tutorial, "How to do math in Java".

Scope of variable


Every programming language variables will have their own scope in the code. You can think of it as the region where the variable can be used. If the scope of a code section is outside the specified scope for a variable, then the variable cannot be used at that region. More info regarding the scope of a variable will be discussed in a future tutorial. 

Retrieve and use a value stored in a variable


we can retrieve back and use the data that's stored in a variable. If we can't retrieve back and use the data that's stored in a variable, then using variable would be meaningless in programming. You can retrieve a variable data by using its identifier/name at the location that you want to use that data.


Primitive Datatypes 

Now let's start the more technical part of our tutorial. In Java, there're several different kinds of data types. Each with their own unique functions,  behaviour and properties. There's a total of eight primitive data type in Java:

  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean
  • char

Some data type are used to store numeric value while some store character or a sequence of characters. The reason why there are different kinds of data type is that there are many different kinds of data that we programmer might need to store temporarily during the run-time of a program. You'll need to make sure that the value assigned to the variable is in its limit or you'll get a compilation error during compilation.

Error during compilation error if we run the above code


Numbers


The primitive numbers data type is divided into two separate groups;
  1. integer types :
    • Stores a whole number, no matter if it's a positive or negative value. The most crucial part is that it cannot have decimals.
    • byte, short, int and long
  2. Floating-point types
    • Stores numbers with fractional parts and contains decimals.
    • float and double


Integer types


Byte


A byte data type can store a whole number between -128 to 127 (size of 2^8). 

declaring a byte variable and output it

Exceeding maximum value will produce error
The number exceeded the maximum value for Byte.


Short


A short data type can store whole numbers in the range of -32768 to 32767 (size of 2^16).

Declaring and outputting a short data type.
The second variable is invalid.


Int


An int (as in integer) data type variable, can store a whole number that's in the range of -2147483648 to 2147483647 (size of 2^32). Int is the most used data type in programming compared to the previous two data types as programmers these days usually don't really need to care much about memory optimisation. 

Back In the early days of software development, computers don't have much memory and the computation power as we have now. That's why programmers need to optimise the memory used by a program. If they didn't manage the program's memory correctly, the program might run out of memory and failed to run successfully. 

Declaring integer value. The first variable is valid,
while the second one is invalid for each section.
In the first section, the 2nd variable exceeded the max value,
While in the second section the value is less than the min value


Long


A Long data type variable can store a whole number between -9223372036854775808 to 9223372036854775807 (size of 2^64). This variable, as the size says for itself, used to store a large integer number. But, you'll need to include the character "L" at the end of the number to indicate its a Long number. You can also use the lowercase "l" for it, but it'll be hard to differentiate it with one, "1". So using the capital letter "L" will make it easier to be distinguished.  

Declaring long variables, the 1st variable in the 1st and 2nd section is valid.
While the 2nd and 3rd variable of both section is invalid.
The 2nd variable didn't include an"L" character at the end,
while the 3rd variable exceeded and lower than the max and min value


Floating-point Types


Float


This data type can store fractional number from 3.4e−038 to 3.4e+038 (size of 2^32). 1 bit for the sign bit, 8 bits of exponent, and 23 bits of the significand (or by following a scientific-notation number, 2.33728*1012 where the "33728" part is the significand). You'll also need to remember to add the character "f" at the end of the value. The "e" sign represents a scientific notation represents the Euler's number to indicate the power of 10.

Declaring the float variables. Remember to always add an "f"
character to the end of the value.


Double


While a double data type can store fractional number from 1.7e−308 to 1.7e+308(size of 2^64). 1 bit is for the sign bit, 11 bits of exponent, and 52 bits of significand. Although it's not a requirement, it's recommended that you'll also need to include a "d" character to the end of the value.

Declaring and assigning value into the variable.
As you can see the "d" character is not required.


But which one to use?


Since the precision of a floating-point value indicates the number of digits the value can have after the decimal point. The precision for a Float is 5 while a double variable precision is 15 digits. Therefore, it's safer to use double for most calculation.


Booleans


A boolean variable can only store 2 value, true and false. Booleans are typically used for conditional statements. A conditional statement will be explained in a later tutorial, for now just think of a conditional statement as a code that lets us run sequence lines of code when a particular condition is met. 

There are two types of boolean data type in Java, boolean (primitive type) and Boolean (reference type or object). The primitive one has lower memory expenses, while the second one provides more useful methods. If you just want to store the value "true" and "false" then you can go with the primitive type, boolean. 

Declaring and assigning values into the boolean variables.


Char


This data type is used to store a single character. The character must be surrounded by single quotes, such as 'a' or 'S'. This datatype could also store ASCII value from the range of 0-127 or 128 different characters in total. But even after exceeding the value 127, char can still store the value as long as the number size is below 2 bytes (2 ^ 16 or to 65535).

Declaring char variables


Non-primitive data types


String


The String data type is used to store a sequence of character (text). The maximum length of the number of characters is 2147483647 ((2^32)-1, the positive range of an int data type).

Declaring String variables



#Extra info


Since String is so much used in Java, some of the programmers call String the "special ninth type". 

A String data type is actually a primitive datatype, as it holds the reference to an object
located in the heap memory. There're other non-primitive data types such as Arrays, Classes, Abstract, Interface, etc. But these will be explained in a future tutorial. 


Well, that's all for this tutorial. I hope now you know the concept of a variable, its uses, the different type of it and when to use a specific data type. As always if you find this tutorial useful, please share it with other people that might need it or find it interesting. Thanks for reading and if you have any suggestions, critics or questions that you want to talk about, feel free to post a comment in the comment section below. In the next tutorial, I'll be teaching you how to print text or numbers with different kinds of ways in Java. So stay tuned.

No comments:

Post a Comment