← Java

Java · 02 / 18

Variables and data types in Java

Distinguish primitive values, text and missing references.

  • Small
  • Basics
  • 15 min

Prerequisites: Install Java and run the first program

A type describes which values a variable can hold. int and long store integers, double stores floating-point numbers and boolean stores true or false. String represents text. String is a reference type. It can refer to an object or be null. Primitive types such as int cannot be null.

Example files

01Declare values

The type precedes the name. = assigns the initial value. final prevents later reassignment. We use long with integer cents for stored money here. Display formatting can represent the amount differently.

Main.java · javaOpen file
public class Main {
  public static void main(String[] args) {
    final String title = "Roof";
    long costCents = 12990;
    boolean done = false;
    String contractor = null;
    String display = contractor == null ? "unknown" : contractor;
    System.out.println(title + ": " + costCents / 100.0 + " EUR, " + display);
    System.out.println(done);
  }
}

Run / check

java Main.java

02Understand integer division

costCents / 100 would discard the fractional part when both operands are integers. Dividing by 100.0 produces a floating-point calculation. Later, money rules call for BigDecimal or exact integer-cent arithmetic.

03Handle missing values

contractor is null. We check that text is present before using it. Unlike Dart’s String?, Java’s simple String type does not include an equivalent built-in null marker. You must handle the boundary explicitly.

Expected result

Roof: 129.9 EUR, unknown

Your exercise

Compare the output of 12990 / 100 and 12990 / 100.0.

Show the solution and explanation

The first output is 129 and the second 129.9. Operand types affect the calculation. Converting only after integer division would not recover the discarded fractional part.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.