Java provides a range of data types that can be used to store different types of values. Here are the basic data types in Java:
byte: A byte is a primitive data type that can store integer values between -128 and 127. It is commonly used for low-level programming where memory usage is a concern.
short: A short is a primitive data type that can store integer values between -32,768 and 32,767. It is also used for low-level programming, but for values that require more space than a byte.
int: An int is a primitive data type that can store integer values between -2,147,483,648 and 2,147,483,647. It is the most commonly used data type for integers in Java.
long: A long is a primitive data type that can store integer values between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. It is used for storing large integer values that cannot be stored in an int.
float: A float is a primitive data type that can store floating-point values with up to 7 digits of precision. It is used for storing values that require decimal places, but do not require a high degree of precision.
double: A double is a primitive data type that can store floating-point values with up to 15 digits of precision. It is used for storing values that require decimal places and a high degree of precision.
boolean: A boolean is a primitive data type that can store only two values: true and false. It is used for storing Boolean values, such as the result of a comparison.
char: A char is a primitive data type that can store a single character. It is used for storing characters, such as letters, numbers, and symbols.
Here’s an example Java program that demonstrates the use of these data types:
public class DataTypes {
public static void main(String[] args) {
byte myByte = 127;
short myShort = 32767;
int myInt = 2147483647;
long myLong = 9223372036854775807L;
float myFloat = 3.14159f;
double myDouble = 3.14159265358979323846;
boolean myBoolean = true;
char myChar = 'A';
System.out.println("Byte: " + myByte);
System.out.println("Short: " + myShort);
System.out.println("Int: " + myInt);
System.out.println("Long: " + myLong);
System.out.println("Float: " + myFloat);
System.out.println("Double: " + myDouble);
System.out.println("Boolean: " + myBoolean);
System.out.println("Char: " + myChar);
}
}
This program declares variables of each data type and assigns them values. It then prints the values to the console using the System.out.println method. Note how the program uses the appropriate data type for each value, and how it declares a long value with the L suffix to indicate that it is a long value.