Аккаунт Войти / Регистрация
Тема
Размер текста
Variables and Constants in Java

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: myVar and myvar are 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: true or false.
  • 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 L on initialization).
  • float — 32-bit floating point number (suffix f on 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, totalPrice instead of tp).
  • Declare variables in the minimally necessary scope.
  • Constants — in uppercase with underscores: MAX_USERS.

Homework

Check yourself — complete the tasks:

  1. Declare variables of all primitive types in Java and output their values to the console (for long and float use the suffixes L and f respectively).
  2. Write a program that calculates the volume of a rectangular prism: input sides a, b, c (as int) and outputs volume (dynamic initialization).
  3. 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.
  4. 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).
  5. 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?

Оставить комментарий

Мой канал в социальных сетях
Отправляя email, вы принимаете условия политики конфиденциальности

Полезные статьи:

Pointers, functions, and execution control in Go vs Java | Types - Language
Series: Go for Java Developers — analyzing pointer, closures, defer, panic/recover In this article, we will analyze how Go manages the state and lifecycle of functions. A feature of Go is the ease of…
Multithreading in Go and Java: types of tasks and solution patterns
Multithreading is not just about "starting a million threads and letting them calculate". It is the art of efficiently using CPU and memory resources, safely processing data, and properly distributing…
Java under the Microscope: Stack, Heap, and GC using Code Examples
Diagram - Java Memory Model - Heap / Non-Heap / Stack Heap (memory for objects) Creates objects via new. Young Generation: Eden + Survivor. Old Generation: objects that have survived several GC c…

Новые статьи:

Concurrency is not about “starting many threads”. It’s about agreements between them. Imagine a restaurant kitchen: — cooks (threads / goroutines) — orders (tasks) — and the main question: how do th…
When HashMap starts killing production: the engineering story of ConcurrentHashMap
Imagine a typical production service. 32 CPU hundreds of threads configuration / session / rate limits cache tens of thousands of operations per second And somewhere inside — a regular Map. At first…
Zero Allocation in Java: what it is and why it matters
Zero Allocation — is an approach to writing code in which no unnecessary objects are created in heap memory during runtime. The main idea: fewer objects → less GC → higher stability and performance. …