Chapter 1 |
Variables
As many other programming languages, Java uses variables (a named memory location) to store values.
PS! Pay attention, the variable names must meet the following rules:
- use camel case notation;
- do not contain special characters or spaces;
- do not start with a digit.
Variables must be declared before they are used.
To use a variable in Java, we have to declare it by telling the compiler not only the name of a variable (as in Python), but also the type of data to be stored there. This is called variable declaration.
Here is an example of a variable declaration which will hold a text (string):
String var;
However, the statement says nothing about the value. To do so, an assignment statement must be used:
var = "Hi!";
The previous two lines can be merged:
String var = "Hi!";
In Python, it is possible to declare several variables on the same line using a semicolon, e.g. a = "Hi!"; b = "World!"
. In Java, we can also declare several variables on the same line but only if they are of the same data type:
String var1 = "Hi!", var2 = "World";
PS! We can declare a variable once. If we try to do it twice, Java will report an error.
Chapter 1 |