We are slowly getting to something more interesting and useful. Variables, the basic and probably the most frequently used thing in java.  They allow storage of various types of data. We ca distinguish two phases of variable creation:

  • Declaration – here we specify the type and name of the variable
  • Initialization – assigning a variable value

Here is an example:

Starting from the beginning, we create a class Variables, and in it we create the main () method. Next, we are declaring the int type and we name it myNumber, and in the next line we give myNumber the value 5 (initialization).

Of course, we can make two in one line:

The scheme is as follows:

We can declare several variables next to each other, as well as assign an already initiated variable to other variables, all of this is shown in the example below.

The important thing is that the operation number2 = number1 is one-off. If we change the value of the variable number1, the number2 will not change its value.

It is time to write something fun, it lets add two integers.

We declare and give a value to two integers a and b, and then display the result of this action. Note how the operator + works this time, the text placed in quotes is displayed in the normal form and the result is the sum of two numbers. This is due to the fact that the plus is used to concatenate (combine) the strings.

We are working with variables here. It is worth mentioning their opposites – final variables. The final keyword is placed before the variable type. The variable declared in this way can only be initiated once (anywhere). A subsequent attempt to assign a new value will end with an error and the program will fail to compile.

The Java naming convention speaks of using only uppercase letters and numbers for them, and for separation use an underscore.

Chains of characters are declared like other variables or final variables, first by giving the type of String (with a capital letter), and then comes the text between the quatation marks.

The important thing remember is that Strings can not be modified directly. This can be avoided in several ways. We can combine or concatenate using the + operator.

In the above example, the substring () method is probably a surprise to you. After running the program, it is easy to guess its operation.

LEAVE A REPLY

Please enter your comment!
Please enter your name here