Beruflich Dokumente
Kultur Dokumente
When we did this, we said that the name of the variable was given-was predefined.
Like M1 on a calculator you might have, or x, as in the example above.
It is like, I want to buy a new module to extend the calculator
with a new variable to store a value.
But when buying this module, the name of the variable
is predefined from factory.
Now what we want to do is to have variables where we can really
choose the names ourselves.
You can visualize something like below, where you can
compose the characters for the name.
But you should be able to make names of any length.
Not like in this example, where the image suggests
that the name has to be of length four.
It can be of any length.
So in Java, when we want to use a variable,
we have to introduce it first with a declaration.
The declaration has to include first the data type of the variable,
but so far, we haven't seen data types in detail.
We have seen just the type of Boolean values.
You remember, the one with two values, true and false.
And we have also worked with numbers, and we
will see elsewhere that there are several data
types provided for numbers in Java.
For the moment for simplification, imagine
that we have one data type called "int." "int" has
as elements, both positive and negative integers, within some bounds.
So the declaration consists of the name of the type followed
by the variable name and a semicolon.
The variable name can be freely chosen with some restrictions.
On occasions instead of name, we also call it identifier.
Now, how can we build names for variables?
In essence, names are words that have to follow some rules,
and here are some rules.
Names have to start with a letter or an underscore symbol,
and they can contain letters-- small or capital letters-- digits,
and the underscore symbol.
Other special symbols are not allowed.
An exception is the dollar sign that is used
at the beginning for automatically-generated variables.
So "n" and "_n" are legal names, whereas "n?" is not.
So you cannot have a digit at the beginning of a name.
"n1" is legal, and "1n" is not.
Further, there are some words that are prohibited,
such as reserved keywords like "int" or "boolean," or literals,
like "true" and "false."
So you cannot have "int" as a name for a variable, or "true."
Further, there cannot be any space in a name.
Here we see a correct example-- "noMore" written together is correct,
and "no More" separate is not.
It would be two names, but the declaration is not correct.
This is not the correct way to declare two variables.
One way of declaring two variables is like we see here-- "int no;"
and "int more;".
And finally, it is an error to have declarations
for the same name in the same scope.
More about scopes later on.