Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Types of variables. Declarations.

Algorithms and programming languages | Fundamentals of programming I | Student is obliged to write down and run this program by himself | Data in a program (variables and literals) | Operations on data (operators and expressions) | Fundamentals of programming II | Write down and run this program on your computer | Write down and run this program on your computer | Introduction to objects | The first program |


Читайте также:
  1. A The following are dictionary definitions of different types of markets.
  2. A) two types of combinability with other words
  3. Ask different types of questions to the text and answer your groupmates’ questions.
  4. B. Some types of printed material
  5. B1 Description of asset types
  6. Basic Types of Bipolar Transistor
  7. Basic Types of Political Systems


As opposed to the literals, types of variables must be specified in declarations.

A declaration of a variable (constant) defines its name, type and possibly some other properties which may be important if the variable (constant) is a field of a class.


Simplified syntax of a declaration may be depicted as follows:

type_name variable_name;


For example,

int a; // declaration of an integer variable a
char c; // declaration of a variable which stores Unicode characters
double price; // declaration of a variable of the type double, named price

The declaration of a variable may specify its initial value.

Initialization of a variable means setting its initial value in the declaration.

 

The syntax of the declaration with initialization is:

type_name variable_name = expression;

 

For example:

int a = 3;

is an abbreviated form of:

int a;
a = 3;

In this case the initializing expression was a literal. In general it may be an arbitrary expression (in particular a method invocation).

For example:
int a = 3;
int b = a + 1; // declaration of variable b and setting its value to 4

Note, that the use of the variable a in the initializer expression of the variable b is possible, because the declaration of the variable a appears before its first use in the initializer expression.

Constants are declared with the keyword final.

The value of a constant can be set only once and it cannot be modified later.

 

To declare a constant we write:

final type_name constant_name [ = expression ];


Initialization (given in square braces) is optional, but it is important to set the value of the constant only once. However, constants are mostly initialized in the declarations.

For example:

final int NUM = 55;
final double PI_SMALL = 3.14;
final char C;
...
C = 'c';


Declarations of variables and constants which refer to objects are noted analogously.
If the type of the variable x is int we write:

int x;

Similarly, if s is the name of the variable referencing to an object of the class String, we write:

String s;
Button b;

Good programming style rules recommend putting declarations one per single line together with a comment describing the meaning of the variable, especially when its application is not clear from its name.

It is possible to declare a number of variables of the same type in a single declaration by specifying them (together with possible initializers) on the list separated with commas. For example:

int num = 1, count, ff = 10;
Button b1, b2, b3;

A programmer must remember to declare all variables in a program.

Declarations must precede the use of variables and constants in the instructions of a program.
It does not mean however, that declarations must precede all the instructions of a program.
On the contrary: variables and constants are usually declared close to the place of their first use, which makes the source code clearer.

 

Consider an example similar to the program for calculating the price of a computer from our initial lectures:

public class CompPrice { public static void main(String[] args) { int cProc = 700; // CPU price int cPly = 500; // mainboard price int cPam = 300; // prices of other components... int cDysk = 400; int cInn = 500; final double VAT = 1.22; // VAT tax // calculate price of the computer without a monitor double cKomp = (cProc + cPly + cPam + cDysk + cInn) * VAT; System.out.println("The price of the computer without a monitor is:"); System.out.println(cKomp); int cMon = 1100; // monitor price net cKomp = cKomp + cMon * VAT; // price of the computer with monitor System.out.println("The price of the computer with the monitor is:"); System.out.println(cKomp); }}


Note that lack of the keyword int before the variable cMon makes it undeclared.

cMon = 1100; // monitor price netcKomp = cKomp + cMon * VAT; // price of the computer with monitor

The compiler detects this error and prints the message:


CompPrice.java:19: cannot resolve symbol
symbol: variable cMon
location: class CompPrice
cMon = 1100; // monitor price net
^
CompPrice.java:20: cannot resolve symbol
symbol: variable cMon
location: class CompPrice
cKomp = cKomp + cMon * VAT; // price of the computer with monitor
^
2 errors

 

The message "cannot resolve symbol" is encountered quite frequently. Usually it means that we are using some name which a compiler cannot identify (most often it is the use of an undeclared variable). A typical source of such errors are misspelled names (lowercase vs. uppercase letters).

Java differentiates lowercase and uppercase letters in names of variables, constants, methods and classes.

 

 

Identifiers


Names of variables, constants, methods and classes are called identifiers.
An identifier begins with a letter or underscore (the _ character) followed by a sequence of alphanumeric characters (letters and digits) or underscores.
The keywords of the Java language cannot be used as identifiers.
see Java reserved words

Naming conventions:

 

Remark: the convention of starting each component with capital letter is called the hungarian notation.

 


Дата добавления: 2015-11-16; просмотров: 78 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Types. Primitive types.| More on operators and expressions

mybiblioteka.su - 2015-2024 год. (0.006 сек.)