Java ProgrammingLearn Variables and Data Types in Java

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.

Valid Java Identifiers:

  • May contain lowercase, uppercase letters, underscores, dollar signs, and digits.
  • Must start with a letter (lowercase or uppercase), underscore, or dollar sign.
  • Must not be a reserved word. The reserved words in Java are: abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, enum, else, extends, false, final, finally, float, for,goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, true, try, void, volatile, and while.
  • Distinguish the letter case; as Java is case-sensitive.

Data Types

The java supports the following data types:

Data Type Keyword Range
Boolean boolean N/A
Character char 0 to 65535
Byte byte (-128) to +127
Short Integer short (-32768) to +32767
Integer int (−2,147,483,648) to +2,147,483,647
Long Integer long (−9,223,372,036,854,775,808) to +9,223,372,036,854,775,807
Floating Point float 32-bits IEEE 754 to 32-bits IEEE 754
Double double 64-bit IEEE 754 to 64-bit IEEE 754

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:

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

int count;

This declares a variable named count of type Integer.

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

float width;

Variable Assignment

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

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

width = 5.6;

Java Programming Course for Beginner From Scratch

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:

int input_num = new Scanner(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:

package readinput;
import java.io.IOException;
import java.util.Scanner;
public class ReadInput
{
        public static void main(String[] args) throws IOException
        {
                System.out.print("\nEnter a number: ");
                float width = new Scanner(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:

1

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

import java.util.Scanner;

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

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:

float width = new Scanner(System.in).nextFloat();

This is equivalent to saying:

float width;
width = new Scanner(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.

So, see you there!!!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -