THINK FIRST·CODE LATER

← All labs

When int is not big enough: overflow

Problem

Write Overflow: read two integers and print their product computed as int, as long (widening before multiplying), and widened after multiplying:

int product:  -1794967296
long product: 2500000000
widened too late: -1794967296
Overflow happened: true
int range: -2147483648 to 2147483647

(for 50000 50000). Explain why long wrong = a * b; does not help.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l3-4-data-1.txt

50000 50000
What your program must print for l3-4-data-1.txt
int product:  -1794967296
long product: 2500000000
widened too late: -1794967296
Overflow happened: true
int range: -2147483648 to 2147483647

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l3-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content l3-4-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.