int num1 = 10;
int num2 = 3;
double result = (double) num1 / num2;
System.out.println(result);
// Output: 3.3333333333333335
Why does casting work? When you write (double) num1 / num2, Java converts num1 to a double first. Then, since one side is a double, Java automatically promotes the other side too. Now it is double / double, which keeps the decimal.
Common Mistake: Writing (double)(num1 / num2) does NOT work! The integer division happens first inside the parentheses (10 / 3 = 3), then you cast 3 to 3.0. The decimal is already lost.
Modulo (%) — The Remainder Integer Division Throws Away
// Integer division gives the quotientint quotient = 10 / 3; // 3// Modulo gives the remainderint remainder = 10 % 3; // 1// Together they tell the full story:// 10 = 3 * 3 + 1
10 / 3 = 3(quotient — how many times 3 fits into 10)
10 % 3 = 1(remainder — what is left over)
Think of it like long division: 3 goes into 10 three times (9), with 1 left over.
Tip: The modulo operator % is very useful for checking if a number is even or odd: num % 2 == 0 means even, num % 2 != 0 means odd.
Enter any two integers and click Divide to see the truncation in action.