What you'll learn

  • The eight primitive types and when to use each
  • How var works
  • Integer vs decimal arithmetic (and its traps)
  • Everyday String methods, formatting and text blocks
  • Why you compare Strings with equals()

Every program works with data: quantities, prices, names, flags. A variable is a named box that holds a value. In Java, every box has a type that says what kind of value it can hold — and the compiler checks it for you, catching many mistakes before your program ever runs.

Declaring variables

int quantity = 24;          // type, name, value
double price = 8.50;
String customer = "Acme";
quantity = 30;              // change the value later

Names start with a letter, use camelCase by convention (orderTotal, not order_total), and are case-sensitive.

The primitive types

TypeHoldsExample
intwhole numbers (±2 billion)int lines = 3;
longvery large whole numberslong id = 9_000_000_000L;
doubledecimal numbersdouble price = 8.50;
floatsmaller decimals (rarely needed)float f = 1.5f;
booleantrue / falseboolean paid = false;
charone characterchar grade = 'A';
byte, shortsmall whole numbersused for binary data

Everything else — String, lists, your own classes — is an object (a reference type).

Note: For money in real applications use java.math.BigDecimal, not double. Doubles are approximations: 0.1 + 0.2 is 0.30000000000000004.

var: let the compiler work out the type

var customer = "Acme Ltd";   // String
var lines = 3;               // int

var (Java 10+) only works for local variables with an initial value. The type is still fixed — var just saves typing. Use it when the type is obvious from the right-hand side.

Arithmetic and its traps

System.out.println(10 / 3);     // 3     — int / int is integer division
System.out.println(10 / 3.0);   // 3.333 — one decimal operand makes it decimal
System.out.println(10 % 3);     // 1     — remainder
int count = 5;
count++;                        // 6
count += 10;                    // 16

Integer division silently drops the fraction, which is a classic source of bugs in averages and percentages. Make one side a double when you need decimals.

Strings

A String is text, written in double quotes. Strings are immutable: methods return a new String rather than changing the original.

String order = "  po-4471  ";
String clean = order.trim().toUpperCase();   // "PO-4471"
clean.startsWith("PO");                       // true
clean.replace("-", "_");                      // "PO_4471"
clean.length();                               // 7
clean.substring(3);                           // "4471"
String.join(", ", "a", "b", "c");             // "a, b, c"

Formatting

String summary = String.format("%s ordered %d lines worth %.2f", "Acme", 3, 204.0);
// Acme ordered 3 lines worth 204.00

%s is text, %d a whole number, %.2f a decimal with two places.

Text blocks (Java 15+)

Multi-line text — JSON, SQL, XML — without escaping every quote:

String json = """
        {
          "order": "PO-4471",
          "inStock": true
        }
        """;

Comparing Strings: equals, never ==

String a = "boomi";
String b = new String("boomi");
a.equals(b);   // true  — same text
a == b;        // false — different objects

== checks whether two variables point to the same object; equals checks whether they contain the same text. Always use equals (or equalsIgnoreCase) for Strings.

The full example

// Basics.java — variables, primitive types, var and strings.
public class Basics {

    public static void main(String[] args) {
        // Primitive types hold simple values
        int quantity = 24;
        double price = 8.50;
        boolean inStock = true;
        char grade = 'A';
        long bigNumber = 9_000_000_000L;   // underscores make big numbers readable

        // Arithmetic
        double total = quantity * price;
        System.out.println("Total: " + total);            // Total: 204.0
        System.out.println("10 / 3 = " + (10 / 3));       // integer division: 3
        System.out.println("10 / 3.0 = " + (10 / 3.0));   // 3.3333333333333335
        System.out.println("10 % 3 = " + (10 % 3));       // remainder: 1

        // var lets the compiler work out the type (Java 10+)
        var customer = "Acme Ltd";        // String
        var lines = 3;                    // int

        // Strings are objects with lots of useful methods
        String order = "  po-4471  ";
        String clean = order.trim().toUpperCase();
        System.out.println(clean);                         // PO-4471
        System.out.println(clean.startsWith("PO"));        // true
        System.out.println(clean.replace("-", "_"));       // PO_4471
        System.out.println(customer.length() + " characters");

        // Formatting
        String summary = String.format("%s ordered %d lines worth %.2f", customer, lines, total);
        System.out.println(summary);

        // Text blocks (Java 15+) for multi-line strings
        String json = """
                {
                  "order": "PO-4471",
                  "inStock": true
                }
                """;
        System.out.print(json);

        // Comparing strings: use equals, not ==
        String a = "boomi";
        String b = new String("boomi");
        System.out.println(a.equals(b));   // true
        System.out.println(a == b);        // false — different objects

        System.out.println(grade + " " + bigNumber + " " + inStock);
    }
}

Run it with java Basics.java and compare the output with the comments.

Try it yourself

Given String raw = " Acme Ltd , AX-200 , 24 ";, print the customer, SKU and quantity on separate lines, trimmed, and the quantity multiplied by 2.

Show a solution
String raw = "  Acme Ltd , AX-200 , 24 ";
String[] parts = raw.split(",");
String customer = parts[0].trim();
String sku = parts[1].trim();
int qty = Integer.parseInt(parts[2].trim());
System.out.println(customer);
System.out.println(sku);
System.out.println(qty * 2);   // 48

split breaks a String into an array; Integer.parseInt turns text into a number.

Key takeaways

  • Every variable has a type; primitives hold simple values, everything else is an object.
  • Watch integer division, and use BigDecimal for money.
  • Strings are immutable and full of useful methods; text blocks make multi-line text easy.
  • Compare Strings with equals, not ==.

Example files