Variables

VariablesDekor okno

They allow you to store data of different types. There are two phases of a variable:

Declaration – here we define the type and variable name
Initialization – giving value to a variable

public class Variables {
public static void main (String [] args) {

int number;                                  // Declaration

number = 5;                                 // Initialization
}
}

 

Create a class variables, and in it we create a method main (). It is followed by declaring a variable of type int and called number (declaration), and in the next line gives it a value of 5 (initialization). Of course, we can make the above two statements in one line:
public class Variables {
public static void main (String [] args) {
char character = ‚A’;
}
}

Program that adds two integers

public class Calculator {
public static void main (String [] args) {
int a = 4;
int b = 6;
System.out.println ( „a+ b = „+ (a + b));
}
}

We declare and assign a value of two variable complete a and b, and then display the result of this action. The text in quotes is displayed in normal form but as a result of the sum of the two numbers. This is due to the fact that the plus is used to concatenate (combine) strings.

Permanent
They differ keyword final placed before the variable type. Declared thus variable may be the only time, in any place, initiated. A later attempt to assign it a new value results in an error and the program does not even pass compilation.

public class constantly {
public static void main (String [] args) {
final double Number_PI = 3.14;
final int constantly2;
Number_PI = 8;                        // Error variable is initialized
constantly2 = 3;                               // So you can do – first assignment
   }
}

 

 

Cookies help us deliver our services. By using our services, you agree to our use of cookies. More Info | Close