Java Essentials: Variables and Data Types

Site Admin · 11 Sep 2026 · 9 views

Declaring Variables

A variable is a named container in memory that holds a value of a fixed type. In Java you write the type first, then the name, then an optional initial value. Java is statically typed, which means the compiler checks the type of every variable before the program even starts running.

int age = 30;
double price = 19.99;
boolean isActive = true;
String name = "Ada";
char letter = 'A';

In the sample, String values are wrapped in double quotes while characters use single quotes. Java differentiates them strictly: single quotes always mean char, double quotes always mean String.

Primitive Data Types

Java has eight primitive types. Four of them store whole numbers: byte 8 bits, short 16 bits, int 32 bits, and long 64 bits. Two store decimal numbers: float and double. One stores a true or false value: boolean. One stores a single Unicode character: char. In practice you will use int for counts, double for measurements, and boolean for yes or no flags.

  • Naming rules - names start with a letter, an underscore, or a dollar sign and are case sensitive.
  • Default values - numbers default to 0, booleans to false, and references to null.
  • Local scope - a variable declared inside a method only exists inside that method.

Reference Types and Strings

Objects are held in variables of reference type. The variable stores a reference, like a download link, rather than the object itself. The String type is the most common reference type. Strings are created with a literal, but they are still objects with useful methods such as length() and toUpperCase().

String city = "Tokyo";
int size = city.length();
System.out.println(size);

Converting Between Types

Widening conversions, like turning an int into a double, are automatic because no detail is lost. Narrowing conversions need an explicit cast because data can be truncated.

int count = 42;
double converted = count; // widening, safe
int restored = (int) converted; // narrowing, needs a cast

Key Points

  • Java is statically typed, so every variable declares its type up front.
  • The eight primitives cover numbers, decimals, booleans, and characters.
  • Strings are immutable objects with many built-in methods.
  • Widening happens automatically, while narrowing requires a cast.
Share this post:

Comments (0)

Please login or register to comment.