HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to JavaVariablesData TypesOperatorsStringsArraysLists (ArrayList)Conditions (if / switch)Loops (for / while)MethodsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & List
🔁 Condition & Loop
🧩 Method & Class
Java›Variables

Variables

Typed variables (int, double, String, boolean), final constants, and naming.

Simple enough for a 5-year-old to understand

Typed variables

Example code
1
public class Main {
2
public static void main(String[] args) {
3
int age = 36;
Integer.
VariableInteger.
4
double height = 1.72;
Decimal.
VariableDecimal.
5
String name = "Alex";
Text (String with a capital S).
VariableText (String with a capital S).
6
System.out.println(name + " " + age + " " + height);
Alex 36 1.72
Output / InputAlex 36 1.72
7
}
8
}
VariableOutput / Input
💡 Hint: Java is statically typed: the type of every variable is specified and immutable.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Define and print a String city = "Lisbon".

🎯 Expected output: Lisbon

Loading editor…

About this topic

Java is a strongly typed language: when creating a variable, you must explicitly write its type, and that variable stays that type for its entire lifetime. Those coming from Python or JavaScript might see this as extra work; in return, many bugs are caught at compile time before the program even runs.

There are two categories of types in Java, and the distinction matters. Primitive types — int, double, boolean, char — hold the value directly. Object types — String, ArrayList, and your own classes — point to an object. This distinction determines comparison and copying behavior.

What you will learn

  • Defining a variable by specifying its type
  • The difference between primitive types and object types
  • Defining immutable values with final
  • Type inference with the var keyword
  • Variable naming conventions
  • Default values and the requirement of initial assignment

When to use?

It is a good habit to define any variable whose value will not change later with final: it documents your intent in the code and prevents accidental modification by the compiler.

The var keyword avoids repetition when the type is already obvious on the right-hand side. However, if it makes the type unreadable, writing it explicitly is better; var exists for readability, not for a brevity contest.

Common mistakes

Wrong

int count;
System.out.println(count + 1);

Local variables must be initialized; Java gives "error: variable count might not have been initialized". Class fields get default values, but local variables do not.

Correct

int count = 0;
System.out.println(count + 1);

Wrong

int total = 10;
total = "on";

In Java, a variable's type cannot change; assigning text to a number variable throws the error "error: incompatible types: String cannot be converted to int". This is an error caught at compile time — the program never runs.

Correct

int total = 10;
String label = "on";

Wrong

double price = 0.1 + 0.2;
if (price == 0.3) {
    System.out.println("equal");
}

The double type stores decimals in binary approximately; the sum of 0.1 and 0.2 is not exactly 0.3, and the condition will never run. BigDecimal should be used instead of double for financial calculations.

Correct

double price = 0.1 + 0.2;
if (Math.abs(price - 0.3) < 1e-9) {
    System.out.println("equal");
}

Frequently asked questions

What is the difference between int and Integer?

int is a primitive type, holds the value directly, and cannot be null. Integer, on the other hand, is an object wrapping int, can be null, and is used in collections. When comparing Integers, you must use equals instead of double equals; otherwise, even if the values are equal, the result can be wrong.

What does final actually do?

It prevents a variable from being assigned a new value. For object types, it only fixes the reference, not the contents of the object: you can still add elements to a final list, but you cannot rebind that name to another list.

Is using var good or bad?

It depends. When the type is obvious on the right-hand side, it avoids repetition and cleans up the code. But if a method's return type is ambiguous, the reader is forced to guess the type. Rule of thumb: use var if the type is clear from looking at the line, otherwise use an explicit type.

Summary

In Java, the type of every variable is declared explicitly and is immutable; this ensures errors are caught at compile time. The distinction between primitive and object types determines comparison behavior, and BigDecimal should be used instead of double for financial calculations.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code