int Exercises

Declare an int variable

Create an int variable named age and assign it the value 20. Print the value to the console.

Show answer:
int age = 20;
System.out.println(age); // prints 20

Valid or invalid?

Which of the following values cannot be stored in an int? Explain why

  • 100
  • 2_000_000_000
  • 3_000_000_000
  • -150
Show answer:
100; // ✅ valid

2_000_000_000; // ✅ valid (within int range)

3_000_000_000; // ❌ invalid (greater than Integer.MAX_VALUE)

-150; // ✅ valid

// int values must be between -2,147,483,648 and 2,147,483,647.

Size and limits

Write code to print:

  • The maximum int value
  • The minimum int value
  • The size of an int in bytes
Show answer:
System.out.println(Integer.MAX_VALUE); // returns 2147483647
System.out.println(Integer.MIN_VALUE); // returns -2147483648
System.out.println(Integer.BYTES); // returns 4

String to int

Convert the string "45" into an int and store it in a variable named number

Show answer:
int number = Integer.parseInt("45"); // prints 45

What happens?

What happens when the following code runs? Explain why

int value = Integer.parseInt("hello");
Show answer:

A NumberFormatException is thrown because "hello" is not a numeric string.


int to String

Convert the number 99 into a String and print it

Show answer:
String text = Integer.toString(99);
System.out.println(text); // prints "99"

Compare two numbers

Use Integer.compare() to compare the numbers 8 and 12. Store the result and print it

Show answer:
int result = Integer.compare(8, 12);
System.out.println(result); // prints -1 as 8 is less than 12

Range check

Write code to the maximum and minimum value in the int range

Show answer:
Integer.MAX_VALUE // returns 2,147,483,647
Integer.MIN_VALUE // returns -2,147,483,648

Equality test

Why does this code print false?

Integer a = 100;
Integer b = 200;
System.out.println(a.equals(b));
Show answer:
false; //100 is not equal to 200, so equals() returns false.

Overflow

What happens if you add 1 to Integer.MAX_VALUE? Explain why

Show answer:
-2,147,483,648 // integer overflow causes the value to wrap around to Integer.MIN_VALUE

Leave a Reply

Your email address will not be published. Required fields are marked *

This site builds beginner confidence through fundamental coding concepts and regular practice. Java is the primary language, but the techniques apply across all programming languages.

Learn. Practice. Master

Categories