Variables & primitive types
Computer Science · Java
Question 1 of 10
0What number does this Java code print? public class Main { public static void main(String[] args) { int x = 2; x = x + 5; x = x + 5; x = x + 3; System.out.println(x); } }
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Variables & primitive types explained
In Java every variable must be declared with a type before it is used, and that type cannot change afterwards. Java is statically typed, so the compiler checks each use against the declared type. There are eight primitive types. The ones you will use most are int for whole numbers, double for decimal numbers, boolean for true or false, and char for a single character. A primitive holds its value directly, unlike an object such as a String.
An int is a 32-bit number, so it covers only about minus 2.1 billion to 2.1 billion. Arithmetic that goes past this limit does not raise an error. The value silently wraps around, so Integer.MAX_VALUE + 1 becomes a large negative number. Dividing two ints discards any fraction, so 7 / 2 gives 3. Use a long, with an L suffix on literals, for bigger whole numbers, and convert between types with a cast such as (int) 3.9, which gives 3.
Literals look like this: long big = 3000000000L; double price = 2.5; char letter = 'A'.
int a = 7;
int b = 2;
System.out.println(a / b);
System.out.println(a / 2.0);
char c = 'A';
System.out.println(c + 1);
Worked example
Trace the program above.
- a / b is 7 / 2. Both values are int, so the fraction is discarded and the result is 3.
- a / 2.0 mixes an int with a double, so Java uses decimal division: 3.5.
- A char is a number underneath. 'A' has the code 65, so c + 1 is 65 + 1 = 66.
The output is three lines: 3, 3.5 and 66.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What number does this Java code print?
public class Main { public static void main(String[] args) { int x = 2; x = x * 4; x = x * 6; x = x + 4; System.out.println(x); } }
Medium
What number does this Java code print?
public class Main { public static void main(String[] args) { double d = 3.7; int n = (int) (d * 100); System.out.println(n); } }
Hard
What number does this Java code print?
public class Main { public static void main(String[] args) { int a = 19; int b = 6; double r = (double) a / b; System.out.println(r); } }