Variables and arithmetic
A variable is a named place for a value. In Java every variable has a type, written before its name, and the type decides what the variable can hold:
intholds whole numbers:int age = 15;doubleholds numbers with a fraction:double price = 2.50;Stringholds text:String name = "Ada";
The = sign does not mean "equals" here: it assigns the value on the right to the variable on the
left. You can assign again later, and the old value is replaced.
public class Area {
public static void main(String[] args) {
int width = 7;
int height = 6;
int area = width * height;
System.out.println("Area: " + area);
}
}
+ adds numbers, but when one side is a String it joins text: "Area: " + 42 is "Area: 42".
The other operators are -, *, / and % (the remainder of a division: 17 % 5 is 2).
Dividing whole numbers
When both sides of / are int, Java divides without the fraction: 7 / 2 is 3, not 3.5. The
result is an int even if you store it in a double. To get the fraction, make one side a double:
7 / 2.0 is 3.5.
This program should print the average of three test scores, Average: 6.666666666666667, but it prints
Average: 6.0. Fix the division.
public class Average {
public static void main(String[] args) {
int a = 4;
int b = 7;
int c = 9;
double average = (a + b + c) / 3;
System.out.println("Average: " + average);
}
}