Learn how to Check Number Data Type in Java using range validation. In this program, we check which Java data type can store a given number. The program compares the input value against the ranges of byte, short, int, and long and displays all compatible data types.
Code Explanation (Step-by-Step)
- Create a Scanner object reads the number entered through the keyboard.
- nextLong() method is used to read a number of type long from the user, and the entered value is stored in the long variable m.
- Check the byte range: If the number is between -128 and 127, it can be stored in the byte data type.
- Check the short range: If the number is between -32,768 and 32,767, it can be stored in the short data type.
- Check the int range: If the number is between -2,147,483,648 and 2,147,483,647, it can be stored in the int data type.
- Check the long range: If the number is between -9,223,372,036,854,775,808L and 9,223,372,036,854,775,807L, it can be stored in the long data type .
- Use try-catch: If the user enters text, a decimal number, or a value outside the long range, the catch block displays an error message.
import java.util.Scanner;
public class TestData {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter value: ");
try {
long m = sc.nextLong();
if (m >= -128 && m <= 127) {
System.out.println("byte");
}
if (m >= -32768 && m <= 32767) {
System.out.println("short");
}
if (m >= -2147483648L && m <= 2147483647L) {
System.out.println("int");
}
if (m >= -9223372036854775808L && m <= 9223372036854775807L) {
System.out.println("long");
}
} catch (Exception e) {
System.out.println("Invalid value");
}
sc.close();
}
}
Input :- enter value :2147483647
Output :-
int
long
Advantages of Using Range Validation
Identifies the Appropriate Data Type
• Range validation helps determine whether a number can be stored in a byte, short, int, or long data type based on its value.
Prevents Data Overflow
• By checking the valid range before storing a value, the program avoids overflow and ensures accurate data storage.
Useful for Input Validation
• It helps verify whether user-entered data is valid before performing further processing.
Reduces Runtime Errors
• Checking the range beforehand prevents errors that may occur when assigning a value to a smaller data type.
Supports Efficient Memory Usage
• Selecting the smallest suitable data type can help optimize memory consumption in applications.
Useful in Real-Time Applications
• Range checks are commonly used in form validation, banking systems, data processing applications, and user input verification.
Here are some Java-related programs that will help you understand Java concepts better: