Variables in Java

by E-Computer Concepts October 23, 2019 at 7:08 am

When you learned algebraic equations in school, you used x and y to represent values in equations. Unlike pi which has a constant value of 3.14, the values of x any y are not constant in equations. Java provides constants and variables to store data in programs.

Java allocates memory to each variable and constant you use in your program. As in algebra, the values of variables may change in a program, but the values of constants, as the name suggests, do not change. You must assign unique names to variables and constants. Variable names are used in a program in much the same way as they are in ordinary Algebra.

Each variable used in a program must be declared. That is to say, the program must contain a statement specifying precisely what kind of information (data type) the variable will contain. This applies to every variable used in the program, regardless of the type.

Naming varibales

A Program refers to a variable using its name. Certain rules and conversions govern the naming of variables. You must adhere to rules. Conventions help improve the readability of the program, but following them is not mandatory.

Rules for Naming Variables in Java

A Variable Name:

  • Must not be a keyword in Java.
  • Must not begin with a digit.
  • Must not contain embedded spaces.
  • Can contain characters from various alphabets.

Syntax for Defining Variables

All the attributes of a class are defined as data members. The syntax used to declare a class variable is:

<data type> <variable_name>

As the braces “{ }” are used to mark the beginning and end of a class, a semicolon “;” is used to mark the end of a statement.

Add Comment