- What is a variable
- Variable Declaration Syntax
- Variable Naming Rules
- Examples of Valid Names
- Basic Data Types (Briefly)
- Code — Examples of Types
- Declaration vs Initialization
- Dynamic Initialization
- Scope and Lifetime
- Example: Nested Scopes
- Initialization Inside a Block
- Restriction: you cannot declare the same names in nested scopes
- Constants
- Recommendations
- Homework
- Test — How well did you understand the lesson?
Variables and Constants in Java
Variables in Java — concept, types, scope, and constants
Hello everyone! This is Vitaly Lesnykh. In this lesson, we will discuss what variables are in Java, why they are needed, what types there are, how to declare and initialize them, what dynamic initialization is, scope, lifetime, and constants.
What is a variable
A variable is a named memory cell where you can store a value and then work with it. Variables are needed so that the program can store data and manipulate it.
Variable Declaration Syntax
General: <type> <name>;
// declaration
int a;
// declaration + initialization
int b = 5;
Variable Naming Rules
- Name cannot start with a digit (
1var— error). - Reserved words cannot be used (for example,
if,while,int,break, etc.). - Letters, digits (not at the beginning), symbols
_and$can be used, but the conventional style is camelCase. - Case matters:
myVarandmyvarare different variables.
Examples of Valid Names
int age;
double accountBalance;
String userName;
int _temp;
int $price; // допустимо, но необычно
Basic Data Types (Briefly)
Primitive types are the most commonly used:
- boolean — logical value:
trueorfalse. - byte — 8 bits, range from -128 to 127.
- short — 16 bits.
- int — 32 bits, the most widely used integer type.
- long — 64 bits, for large integers (written with the suffix
Lon initialization). - float — 32-bit floating point number (suffix
fon initialization). - double — 64-bit floating point number, often used for fractions.
- char — character (2 bytes, Unicode).
Code — Examples of Types
boolean flag = true;
byte b = 127;
short s = 32000;
int i = 1_000_000;
long l = 12345678900L;
float f = 3.14f;
double d = 3.1415926535;
char ch = 'A';
Declaration vs Initialization
Declaration reserves a name and type. Initialization assigns a value.
// объявление
int x;
// инициализация (присваивание)
x = 10;
// объявление + инициализация
int y = 2;
Dynamic Initialization
A variable can take a value computed at runtime:
int a = 1, b = 2, c = 3;
int volume = a * b * c; // динамическая инициализация: вычисляем на основе других переменных
System.out.println("Volume = " + volume); // выведет 6
Scope and Lifetime
The scope of a variable is defined by curly braces { ... }. The variable is only accessible within the block where it is declared. When execution leaves the block, the variable is "destroyed" (in the sense of being unavailable).
Example: Nested Scopes
int a = 1;
if (a == 1) {
int b = 2; // b is only accessible within this block
System.out.println(a + b); // OK
}
// System.out.println(b); // ERROR: b is not visible here
Initialization Inside a Block
If a variable is declared above but initialized within the block, its value may change or be reinitialized each time the block is entered.
int b; // declared outside the loop
for (int a = 0; a < 3; a++) {
b = 0; // initialize inside the loop
b++;
System.out.println("a=" + a + " b=" + b); // b will always show 1
}
If b is initialized outside the loop and incremented inside, it will accumulate its value:
int b = 0;
for (int a = 0; a < 3; a++) {
b++;
System.out.println("a=" + a + " b=" + b); // b: 1, 2, 3
}
Restriction: you cannot declare the same names in nested scopes
In Java, you cannot declare a variable with the same name in a nested scope — this will result in a compilation error.
Constants
Constant — a value that cannot be changed after assignment. In Java, the keyword final is used.
final int DAYS_IN_WEEK = 7;
System.out.println(DAYS_IN_WEEK);
// DAYS_IN_WEEK = 8; // ERROR: cannot overwrite a constant
Recommendations
- Choose the minimally appropriate type (do not occupy extra memory unnecessarily).
- Use clear variable names (for example,
totalPriceinstead oftp). - Declare variables in the minimally necessary scope.
- Constants — in uppercase with underscores:
MAX_USERS.
Homework
Check yourself — complete the tasks:
- Declare variables of all primitive types in Java and output their values to the console (for
longandfloatuse the suffixesLandfrespectively). - Write a program that calculates the volume of a rectangular prism: input sides
a,b,c(asint) and outputsvolume(dynamic initialization). - Show an example where a variable is declared outside a block, but initialized inside — demonstrate the difference in behavior when initializing inside and outside a loop.
- Create a constant for the maximum number of attempts (
final int MAX_ATTEMPTS = 3;) and use it in a condition (for example, an attempt counter). - Try to declare a variable with the name of a reserved word (for example,
int if = 5;) — see what error the compiler gives, and write an explanation in the comments to the code.
Tip: place variables as close as possible to where they are used — this makes the code more readable and safer.
Good luck with practice!
Test — How well did you understand the lesson?
Оставить комментарий
Useful Articles:
New Articles: