Variables & data types
Primitive types, Strings, var, casting and the integer-division trap.
Programs work with data. In Java every piece of data has a type, which tells the compiler what kind of values it can hold and which operations make sense. Java checks types at compile time, so many mistakes are caught before your program ever runs.
Declaring variables#
A variable is a named box that holds a value:
int agedeclares a variable of typeintnamedage.= 21assigns it the value 21.- You can declare first and assign later (
int age; age = 21;), but a local variable must be assigned before you read it, otherwise the compiler complainsvariable age might not have been initialized.
You can change a variable's value later, but never its type:
Naming rules and conventions
- Names may contain letters, digits,
_and$, but cannot start with a digit. - They cannot be keywords such as
class,intornew. - Java is case-sensitive:
totalandTotalare different variables. - Convention: variables and methods use
camelCase(totalPrice), constants useUPPER_SNAKE_CASE(MAX_USERS), classes usePascalCase(BankAccount).
var: local type inference
From Java 10 you can write var when the type is obvious from the right-hand side:
The variable still has a fixed static type; var just saves typing. It only works for local variables that are initialised on the same line. Use it when it improves readability, not to hide important types.
Primitive types#
Java has eight primitive types built into the language:
Underscores in numbers (2_000_000) are only for readability; the compiler ignores them.
Everything that is not a primitive is a reference type: String, arrays, and every class you will write. A reference variable holds a pointer to an object rather than the value itself, and can be null (pointing at nothing).
Strings#
Text uses the String class (capital S, it is not a primitive):
Strings are immutable: methods like toUpperCase() return a new string and never change the original. The + operator joins strings, and converts other values to text automatically: "Age: " + 21 gives "Age: 21". There is a whole lesson on strings later.
Casting and conversion#
Java converts automatically when no information can be lost (widening), and demands an explicit cast when it might be (narrowing):
Notice text + parsed + price: because it starts with a String, every + means concatenation, giving "42" + "42" + "19.99".
The integer-division trap#
This surprises almost every beginner:
If both operands are integers, Java does integer division and throws the fraction away. Cast at least one side to double before dividing when you want a fractional result.
Overflow and floating-point surprises#
Primitive numbers have limits. Go past them and they silently wrap around:
- Use
longwhen values might exceed about two billion (e.g. milliseconds, file sizes, populations). Math.addExactandMath.multiplyExactthrow an exception instead of silently overflowing.doublecannot store most decimal fractions exactly. Never usedoublefor money; uselongcents orjava.math.BigDecimal.
Constants with final#
final means "assigned exactly once". Constants shared across a class are usually declared static final (you will meet static later), for example static final int MAX_USERS = 100;.
Putting it together#
Common mistakes#
- Forgetting
Lon large literals:long x = 9000000000;does not compile, because the literal is treated as anint. - Writing
float f = 1.5;: decimal literals aredouble, so write1.5f. - Using
"A"(aString) where you meant'A'(achar). - Expecting
5 / 2to be2.5. - Comparing
Strings with==instead of.equals(). More on this in the strings lesson.
What's next#
You can now store and convert data. Next we combine values with operators: arithmetic, comparisons, logic and more.
Check your understanding
Quick quiz
1.What is the result of
5 / 2when both numbers areint?2.Which keyword declares a variable whose value cannot be reassigned?
3.Which declaration does NOT compile?
Finished reading?
Mark this lesson complete to track your progress.