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?


🌐 На русском
Total Likes:0

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

My social media channel
By sending an email, you agree to the terms of the privacy policy

Useful Articles:

Understanding multithreading in Java through collections and atomics
Understanding Multithreading in Java through Collections and Atomics 1️⃣ HashMap / TreeMap / TreeSet (not thread-safe) HashMap: Structure: array of buckets + linked lists / trees (for collisions). U...
Modern architectural approaches: from monolith to event-driven systems
Introduction Architecture is more than just a way to arrange classes and modules. It is the language a system uses to communicate time. Today, Java developers live in a world where the boundaries bet...
Go ↔ Java: Complete Guide to Runtime, Memory, and Allocator - Part 3
This article is a comprehensive guide to the key aspects of memory and runtime work in Go and Java. We will discuss fundamental concepts: execution scheduler, memory barriers, memory alignment, stack ...

New Articles:

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. ...
Stream vs For in Java: how to write the fastest code possible
In Java, performance is often determined not by the "beauty of the code," but by how it interacts with memory, the JIT compiler, and CPU cache. Let s analyze why the usual for is often faster than Str...
Compiler, Build, and Tooling in Go and Java: how assembly, initialization, analysis, and diagnostics are organized in two ecosystems
This article is dedicated to a general overview of how the compiler, build, and tooling practices are arranged in Go, and how to better understand them through comparison with Java. We will not delve ...
Fullscreen image