Tutorials

Java tutorials

Java

Variables and Data Types in Java

3 min read · 80 views

Every Java program works by storing and manipulating values, and a variable is simply a named location that holds one of those values. Unlike some other languages, Java requires every variable to declare its type upfront, which might feel strict at first but catches a large class of mistakes before the program ever runs.

Declaring a variable

int age = 25;
String name = "Sam";
boolean isActive = true;

Each line follows the same pattern: the type, then the name, then the starting value. Once declared with a type, a variable can never hold a value of a different, incompatible type later in the program.

Primitive types versus objects

Java splits its types into two groups. Primitive types, such as int, double, boolean and char, hold simple values directly and are extremely lightweight. Everything else, including String and any custom class, is a reference type, meaning the variable actually holds a reference pointing to an object stored elsewhere in memory. This distinction explains many small quirks in Java, such as why comparing two String values with == can behave unexpectedly, covered in more depth in the tutorial comparing == and equals in the interview questions section.

Common types

  • int: whole numbers, such as 5 or -20, good for counting.
  • double: numbers with decimals, such as 3.14, needed whenever a fraction matters, like a price.
  • boolean: only ever true or false, used for conditions and flags.
  • char: a single character, such as 'A'.
  • String: text made of many characters, such as "hello".

Type casting

Sometimes a value needs converting between types. Converting from a smaller type to a larger one, like int to double, happens automatically since no information is lost. Going the other way needs an explicit cast, since it might lose precision:

double price = 9.75;
int wholePart = (int) price;  // 9, the decimal part is discarded

The final keyword

Adding final before a variable declaration prevents it from ever being reassigned after its first value is set, which is useful for values that represent a constant, such as a fixed configuration limit:

final int MAX_USERS = 100;

A tip on naming

Clear variable names make code far easier to read months later. totalPrice communicates its purpose instantly, while a name like tp forces anyone reading the code to go hunting for context. Good naming is a habit that pays off every single time the code is revisited.