Integer and floating-point division in Java — Aptitude
Integer and floating-point division in Java: What does this Java program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
What does this Java program print?
public class Main {
public static void main(String[] args) {
System.out.println(5 / 2 + " " + 5 / 2.0 + " " + 5 % 2);
}
}Options
- 2 2.5 1
- 2 2.0 1
- 2 2.5 2
- 2.5 2.5 1
Show the answer and the worked solution
Correct answer: A. 2 2.5 1
Worked solution
- 5 / 2 is int division and yields 2.
- 5 / 2.0 promotes the 5 to double, so it yields 2.5.
- 5 % 2 is the remainder 1, and the three values are joined into 2 2.5 1.
Answer: 2 2.5 1.
The idea
Division stays in the integers only while both operands are integers; a single double operand promotes the whole expression. The arithmetic runs before any concatenation, because / and % outrank +.
Shortcut. Read each piece by its operand types: int ÷ int gives 2, int ÷ double gives 2.5, and 5 % 2 is 1, which matches one option only.
Common trap. "2.5 2.5 1" expects 5 / 2 to give 2.5, as in Python 3; with two int operands Java discards the fraction.
All Programming Fundamentals questions · placement mock tests