Learn Variables and Data Types in Java

In computer programs, data is stored in variables. When we say data, we mean numbers with all their varieties, characters, and strings. These categories classify data into types called Data Types. In Java, each variable can store a specific type of data, and hence should belong to a specific data type. Variables and Data Types will be the topic of today’s article. An important constitutive topic to read. I hope you enjoy it.

Variables

As I told you, variables store data in computer programs. But what is the nature of those variables? Where do they live? And how long do they live?!

Don’t be astonished to hear that talk. Variables actually have life of their own. I will tell you about this life shortly, after we define what variables are.

Variables are segments (locations) in memory that stores data, and are referred to by names. Such names are defined in an operation called declaration. Declaration means to tell the compiler to take into account that a variable with a specific name will be used. As named memory segments, variables by their definition live in memory. A variable’s life starts when it is declared, and is terminated when it is no longer used. Between the start and the termination, a variable is initialized, has data written to it, and read from it.

To declare a variable, you have to specify its name and data type. So, let’s have a look on both.

Variable Names

Can I use any name or any combination of characters to be a variable name? Apparently, No. Your baby, your own baby (could you imagine?), you don’t have absolute liberty to give him any name! This is simply because each country has its own regulations that may ban some names. Usually, governments issue lists of names that are banned for having ridiculous, racial, or sexual meanings in the country’s language. In computer programming, each programming language has its rules for naming variables, functions, classes, and other objects. Such rules include also the list of private (reserved) words that can’t be chosen as identifiers. Java is not an exception to that. It has its own naming rules, and also the list of reserved keywords that are not allowed as identifiers.

The data type determines the amount of memory space that will be allocated to the variable, and the type of information that can be stored in it.

Variable Declaration

To declare a variable in Java, the following syntax is used:

1

DATATYPE VARIABLENAME;

Where:
DATATYPE is either a basic (one of the listed in the above table) or user-defined (will be discussed later when talking about Classes) data type.
VARIABLENAME is any valid Java identifier.

Example

1

intcount;

This declares a variable named count of type Integer.

Example
To declare a variable named width allowing the decimal point:

1

floatwidth;

Variable Assignment

Values are assigned to variables using the assignment operator ‘=’

Example
To assign the decimal value 5.6 to the variable width:

1

width=5.6;

Reading User Input

There are several ways to get input from the user in Java. One of the easiest methods to do so is by using the Scanner class with the System.in object (don’t get confused by theses names; you will know everything in time). The Scanner class has a rich list of methods that parses the input to produce integer, short integer, long integer, float, double, string, etc.

Method

Return Value

Description

nextByte()

byte

Scans the next token of the input as a byte.

nextDouble()

double

Scans the next token of the input as a double.

nextFloat()

float

Scans the next token of the input as a float.

nextInt()

Int

Scans the next token of the input as an int.

nextLine()

String

Advances this scanner past the current line and returns the input that was skipped.

nextLong()

long

Scans the next token of the input as a long.

nextShort()

short

Scans the next token of the input as a short.

For instance, to read an input integer from the user and assign it to the variable input_num:

1

intinput_num=newScanner(System.in).nextInt();

Example
In this example, we are going to prompt the user to enter a decimal number, and then print the input back to the user.

Consider the following code:

1

2

3

4

5

6

7

8

9

10

11

12

packagereadinput;

import java.io.IOException;

import java.util.Scanner;

publicclassReadInput

{

publicstaticvoidmain(String[]args)throwsIOException

{

System.out.print("\nEnter a number: ");

floatwidth=newScanner(System.in).nextFloat();

System.out.println("You entered: "+width+"\n");

}

}

If you run this program in your NetBeans IDE, or in a command-line window, you should get an output like the following:

Note
For the Scanner class to work, we need to import it from the java.util package using the import statement.

1

import java.util.Scanner;

Note
Pay attention to the usage of the + operator to concatenate strings:

1

System.out.println("You entered: "+width+"\n");

Notice that variable declaration and assignment could be done in one statement like what we did in the line:

1

floatwidth=newScanner(System.in).nextFloat();

This is equivalent to saying:

1

2

floatwidth;

width=newScanner(System.in).nextFloat();

Both ways are valid, so you could choose the one you prefer.

Summary
In this article, we have talked about Variables and Data Types.

Variables are named memory locations that stores data while a program is running.

A Variable has a name and a data type.

Before using a variable, it must be declared first.

These are Variables and Data Types. Now, we need to know what to do with those variables and data types. The answer for this question will be in the next article: Using Operators.