Variables and data types
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
Declaring a variable
Java is statically typed. Every variable has a type, and the type cannot change. You write the type, then the name, then optionally a value.
int age = 34;
String city = "Lahore";
double height = 1.78;
boolean student = false;
Primitive types
Java has eight primitive types. They hold simple values directly, and they always start with a lowercase letter.
| Type | Size | Holds |
|---|---|---|
byte | 8 bits | -128 to 127 |
short | 16 bits | -32,768 to 32,767 |
int | 32 bits | about -2.1 billion to 2.1 billion |
long | 64 bits | very large whole numbers |
float | 32 bits | decimal numbers, low precision |
double | 64 bits | decimal numbers, the default choice |
char | 16 bits | one character, such as 'A' |
boolean | n/a | true or false |
In practice you will use int, long, double and boolean nearly all of the time. Anything that is not a primitive is a reference type, such as String or any class. A reference variable holds a pointer to an object, and it can also hold null, which means no object.
A longer example
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
// Literals need the right suffix
long population = 240_000_000L; // underscores help reading
float ratio = 0.5f;
char grade = 'A';
// var lets the compiler infer the type
var count = 10; // int
var message = "Types matter"; // String
// final means the variable cannot be reassigned
final double TAX_RATE = 0.17;
// Integer division and casting
System.out.println(7 / 2); // 3
System.out.println(7 / 2.0); // 3.5
double average = (double) 7 / 2; // cast first, then divide
System.out.println(average);
int truncated = (int) 9.99; // 9, the decimals are cut off
System.out.println(truncated);
// Overflow wraps around silently
int big = Integer.MAX_VALUE;
System.out.println(big + 1); // -2147483648
System.out.println(Math.addExact(5, 6));
try {
Math.addExact(big, 1);
} catch (ArithmeticException e) {
System.out.println("Overflow detected: " + e.getMessage());
}
// Floating point is not exact
System.out.println(0.1 + 0.2); // 0.30000000000000004
// Use BigDecimal for money
BigDecimal price = new BigDecimal("19.99");
BigDecimal total = price.multiply(BigDecimal.valueOf(3));
BigDecimal tax = total.multiply(BigDecimal.valueOf(TAX_RATE))
.setScale(2, RoundingMode.HALF_UP);
System.out.println("Total " + total + ", tax " + tax);
// char is a number underneath
char next = (char) (grade + 1);
System.out.println(next); // B
System.out.println(population + " " + ratio + " " + count + " " + message);
}
}
Walking through it
A whole-number literal like 240_000_000 is an int by default. When the value is too big for an int, or when you want a long, add L. A decimal literal is a double. To make a float, add f. Underscores in numbers are ignored by the compiler and help you count zeros.
var arrives from Java 10. The compiler works out the type from the right-hand side. It only works for local variables that you initialise on the same line. It is still static typing, nothing becomes dynamic.
final on a variable means you can assign it once. The convention for constants is upper-case names. For a true constant shared by a class, you would write static final at class level.
The division lines repeat a trap from many languages. When both operands are int, the result is an int, and the fraction is thrown away. Make one operand a double, or cast one of them. In (double) 7 / 2 the cast applies to the 7 before the division. Casting from a larger type to a smaller one, like (int) 9.99, cuts off the decimals without rounding. Use Math.round if you want rounding.
Overflow is silent. Adding 1 to the largest int gives the smallest one. Java does not warn you. When it matters, use Math.addExact, multiplyExact and their relatives, which throw an ArithmeticException, or use long.
0.1 + 0.2 printing 0.30000000000000004 is a property of binary floating point and not a Java bug. For money, avoid double. BigDecimal stores exact decimal values. Create it from a string, as in new BigDecimal("19.99"), because new BigDecimal(19.99) would capture the inexact double. You must choose a rounding mode when you reduce the number of decimals.
Wrapper classes
Each primitive has a wrapper class: Integer, Long, Double, Boolean, Character. Collections such as List cannot hold primitives, so you write List<Integer>. Java converts automatically between int and Integer. This is called autoboxing. A wrapper can be null, and unboxing a null throws NullPointerException.
Common mistakes
- Integer division when you wanted a decimal result.
- Using double for money.
- Assigning a long to an int without a cast. The compiler refuses, which is good.
- Forgetting that
charuses single quotes andStringdouble quotes. - Relying on overflow not happening. Think about the largest value a variable can see.
Try it yourself
- Declare variables for a product: name, quantity, unit price (as
BigDecimal) and in-stock flag. Print the total price. - Compute the average of three
intvalues correctly, as a double. - Find out what
Integer.MAX_VALUE * 2prints, and explain it.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
// Literals need the right suffix
long population = 240_000_000L; // underscores help reading
float ratio = 0.5f;
char grade = 'A';
// var lets the compiler infer the type
var count = 10; // int
var message = "Types matter"; // String
// final means the variable cannot be reassigned
final double TAX_RATE = 0.17;
// Integer division and casting
System.out.println(7 / 2); // 3
System.out.println(7 / 2.0); // 3.5
double average = (double) 7 / 2; // cast first, then divide
System.out.println(average);
int truncated = (int) 9.99; // 9, the decimals are cut off
System.out.println(truncated);
// Overflow wraps around silently
int big = Integer.MAX_VALUE;
System.out.println(big + 1); // -2147483648
System.out.println(Math.addExact(5, 6));
try {
Math.addExact(big, 1);
} catch (ArithmeticException e) {
System.out.println("Overflow detected: " + e.getMessage());
}
// Floating point is not exact
System.out.println(0.1 + 0.2); // 0.30000000000000004
// Use BigDecimal for money
BigDecimal price = new BigDecimal("19.99");
BigDecimal total = price.multiply(BigDecimal.valueOf(3));
BigDecimal tax = total.multiply(BigDecimal.valueOf(TAX_RATE))
.setScale(2, RoundingMode.HALF_UP);
System.out.println("Total " + total + ", tax " + tax);
// char is a number underneath
char next = (char) (grade + 1);
System.out.println(next); // B
System.out.println(population + " " + ratio + " " + count + " " + message);
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account