Variables and types
In Java, every variable has a type that's fixed when you declare it. The compiler uses those types to catch mistakes before your program ever runs.
Declaring variables
public class Main {
public static void main(String[] args) {
int age = 31;
double price = 59.99;
boolean inStock = true;
char grade = 'A';
String name = "Asha";
System.out.println(name + " is " + age);
System.out.println("Price: " + price + ", in stock: " + inStock + ", grade: " + grade);
age = age + 1; // change the value; the type stays int
age += 1;
age++;
System.out.println("Age now: " + age);
}
}Asha is 31 Price: 59.99, in stock: true, grade: A Age now: 34
The pattern is type name = value;. Once age is an int, it can only ever hold whole numbers:
public class Main {
public static void main(String[] args) {
int age = 31;
age = "thirty-two";
}
}Main.java:4: error: incompatible types: String cannot be converted to int
age = "thirty-two";
^
1 error
error: compilation failedPrimitive types
Java has eight primitive types for simple values:
| Type | Holds | Example |
|---|---|---|
int |
Whole numbers, about ±2.1 billion | 42 |
long |
Bigger whole numbers | 9_000_000_000L |
double |
Decimal numbers (64-bit) | 3.14 |
float |
Smaller decimals (rarely used) | 3.14f |
boolean |
true or false |
true |
char |
A single character, in single quotes | 'A' |
byte, short |
Small whole numbers | (byte) 100 |
Use int for whole numbers, double for decimals and boolean for yes/no, and you'll be right most of the time.
public class Main {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MAX_VALUE + 1); // overflow: wraps around!
long big = 3_000_000_000L; // L marks a long literal
System.out.println(big * 2);
System.out.println(0.1 + 0.2); // floating point is approximate
}
}2147483647 -2147483648 6000000000 0.30000000000000004
Two classic surprises: int silently overflows past its limit, and double can't represent 0.1 exactly. For money, use long cents or BigDecimal.
String: text
String is not a primitive; it's a class (notice the capital S), but Java gives it special syntax:
public class Main {
public static void main(String[] args) {
String first = "Ada";
String last = "Lovelace";
String full = first + " " + last;
System.out.println(full);
System.out.println(full.length());
System.out.println(full.toUpperCase());
System.out.println(full.charAt(0));
System.out.println(full.contains("Love"));
System.out.println("Score: " + 7 + 3); // text first: becomes "73"
System.out.println("Score: " + (7 + 3)); // brackets first: 10
}
}Ada Lovelace 12 ADA LOVELACE A true Score: 73 Score: 10
You'll go much deeper into strings in the arrays and strings lesson.
Arithmetic
public class Main {
public static void main(String[] args) {
System.out.println(7 + 2); // 9
System.out.println(7 / 2); // 3 ← int / int = int (the decimals are dropped)
System.out.println(7 / 2.0); // 3.5 ← one double makes it decimal division
System.out.println(7 % 2); // 1 (remainder)
System.out.println(Math.pow(2, 10));
System.out.println(Math.sqrt(144));
System.out.println(Math.round(2.567 * 100) / 100.0);
}
}9 3 3.5 1 1024.0 12.0 2.57
Integer division (7 / 2 == 3) catches every Java beginner at least once.
Converting between types
public class Main {
public static void main(String[] args) {
int whole = 7;
double d = whole; // widening: automatic and safe
System.out.println(d);
double price = 9.99;
int rounded = (int) price; // narrowing: needs an explicit cast, drops decimals
System.out.println(rounded);
int fromText = Integer.parseInt("42");
double fromText2 = Double.parseDouble("3.5");
String toText = String.valueOf(99);
System.out.println(fromText + 1);
System.out.println(fromText2 * 2);
System.out.println(toText + "!");
}
}7.0 9 43 7.0 99!
var: let the compiler infer the type
Since Java 10, local variables can use var. The type is still fixed; the compiler just works it out from the value:
public class Main {
public static void main(String[] args) {
var count = 10; // int
var name = "Rahul"; // String
var ratio = 0.75; // double
System.out.println(name + " " + count * ratio);
}
}Rahul 7.5
Use var when the type is obvious from the right-hand side.
Constants with final
public class Main {
static final double TAX_RATE = 0.18; // a constant: can't be reassigned
public static void main(String[] args) {
double price = 100;
System.out.println("With tax: " + price * (1 + TAX_RATE));
}
}With tax: 118.0
By convention, constants are written in UPPER_SNAKE_CASE. Variables and methods use camelCase (firstName, totalPrice), and classes use PascalCase (BankAccount).
Practice
- Declare variables for a product's name, price (
double) and quantity (int), and print the total. - Convert the text
"250"to anint, add 50 and print it. - Predict the output of
System.out.println(10 / 4 + 10 / 4.0);, then check it.
1.What does System.out.println(9 / 2); print?
2.Which type should you use for "is the user logged in"?
3.What does var x = 5; declare?