The Code Codex
Theme
← Notes / Fundamentals

note · text29 Sep 2024 · 1 min

Variables and Constants

A variable is a name tied to a memory slot, with a type and a value that can change. A constant is a name whose value is set once and never changes.

Declaring
var count int = 10 // explicit
name := "Douglas" // inferred type (only inside functions)
const MaxRetries = 3 // constant, resolved at compile time
int count = 10; // explicit
var name = "Douglas"; // inferred type (Java 10+, local variables only)
static final int MAX_RETRIES = 3; // constant (class field)
Initial value
  • Go: every variable starts with its type’s zero value: 0, "", false or nil. There is no such thing as a variable “without a value”.
  • Java: class fields get a default value (0, false, null), but a local variable must be initialized before use, or it won’t compile.
Scope

A variable only exists inside the block ({ }) where it was declared. The smaller the scope, the easier it is to know who can change it.

if user, err := find(id); err == nil {
fmt.Println(user) // user and err only exist inside this if
}
What final really guarantees

In Java, final prevents reassigning the variable, but it doesn’t prevent changing the object it points to:

final List<String> names = new ArrayList<>();
names.add("Ana"); // allowed: the object changed
names = new ArrayList<>(); // compile error: reassignment

For an object that truly doesn’t change, use immutable types (List.of(...), records).

In Go, constants can only be values known at compile time (numbers, strings, booleans); there are no struct or slice constants.

See also: Data types and Pointers.