Java Basics: Your First Programs
Variables and Data Types
In this lesson you will
- Declare variables with Java's primitive types and String
- Do arithmetic and understand integer division
- Convert between types with casts and use final constants
Introduction
A variable is a named place that holds a value. Java is a statically typed language: you must say what type of value each variable holds, and the compiler checks that you use it correctly. This catches many mistakes before the program ever runs.
Declaring variables
Write the type, then the name, then the value:
Java
public class Main {
public static void main(String[] args) {
int age = 14;
double price = 4.99;
boolean isStudent = true;
char grade = 'A';
String name = "Asha";
System.out.println(name + " is " + age);
System.out.println("Price: " + price);
System.out.println(isStudent);
System.out.println(grade);
}
}Asha is 14
Price: 4.99
true
AThe main types
Java has eight primitive types. These four cover most of what you need:
| Type | Holds | Example |
|---|---|---|
int | whole numbers (about ยฑ2 billion) | 42 |
double | decimal numbers | 3.14 |
boolean | true or false | true |
char | a single character, in single quotes | 'A' |
Others: long (bigger whole numbers, written like 5000000000L), float, short and byte. String is not a primitive: it is a class that holds text, and its values are in double quotes.
Quick quiz
Which type would you use to store the value 19.99?
Types are enforced
The compiler will not let you put the wrong kind of value in a variable:
Java
public class Main {
public static void main(String[] args) {
int count = "five";
}
}Main.java:3: error: incompatible types: String cannot be converted to int
int count = "five";
^
1 errorOnce declared, a variable keeps its type. You can change its value, but not its type.
Arithmetic
Java
public class Main {
public static void main(String[] args) {
int a = 17;
int b = 5;
System.out.println(a + b); // 22
System.out.println(a - b); // 12
System.out.println(a * b); // 85
System.out.println(a / b); // 3 (integer division)
System.out.println(a % b); // 2 (remainder)
System.out.println(a / 5.0); // 3.4
}
}22
12
85
3
2
3.4Integer division is a classic trap. When both numbers are int, Java drops the remainder: 17 / 5 is 3, not 3.4. Make at least one side a double to get a decimal answer. The % operator gives the remainder, which is handy for testing whether a number is even (n % 2 == 0).
Shortcuts: x += 5 means x = x + 5. x++ adds one, and x-- subtracts one.
Java
public class Main {
public static void main(String[] args) {
int score = 10;
score += 5;
score++;
score *= 2;
System.out.println(score);
}
}32Casting: converting between types
Converting a smaller type to a larger one happens automatically. Going the other way loses information, so you must ask for it with a cast.
Java
public class Main {
public static void main(String[] args) {
int whole = 7;
double wider = whole; // automatic: no information lost
System.out.println(wider);
double price = 9.99;
int cut = (int) price; // cast: the decimals are cut off
System.out.println(cut);
int a = 7;
int b = 2;
System.out.println((double) a / b); // cast before dividing
}
}7.0
9
3.5Casting to int truncates (cuts off) rather than rounds. Use Math.round(price) to round.
Constants with final
final makes a variable impossible to change after it is set. By convention, constants are written in CAPITAL_LETTERS.
Java
public class Main {
public static void main(String[] args) {
final double TAX_RATE = 0.2;
double price = 50.0;
System.out.println(price * (1 + TAX_RATE));
}
}60.0Trying to assign to TAX_RATE again would be a compile error.
var: let Java work out the type
Since Java 10, you can write var for local variables when the type is obvious from the value. It is still statically typed.
Java
public class Main {
public static void main(String[] args) {
var name = "Asha"; // String
var count = 3; // int
var ratio = 0.75; // double
System.out.println(name + " " + count + " " + ratio);
}
}Asha 3 0.75A word about overflow
Each type has limits. An int that goes past its maximum wraps around to a negative number, without any error:
Java
public class Main {
public static void main(String[] args) {
int big = Integer.MAX_VALUE;
System.out.println(big);
System.out.println(big + 1);
}
}2147483647
-2147483648When numbers might be large, use long.
Quick quiz
What does int x = 9 / 2; store in x?
Try it yourself
On your computer, write a program that stores a temperature in Celsius as a double (say 25.0), converts it to Fahrenheit using F = C * 9 / 5 + 32, and prints 25.0 C = 77.0 F. Then change the temperature to an int and see why you must be careful with 9 / 5.
Summary
- Java variables have a fixed type:
int,double,boolean,charandStringcover most needs. - Dividing two
ints drops the remainder. Use adoublefor decimals. - A cast like
(int) priceconverts types and truncates.finalcreates a constant. varlets Java infer the type of a local variable. Integers overflow silently, so uselongfor big values.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading