Certainly! Here are code examples demonstrating the purpose of each Java primitive data type:
public class DataTypePurposeExample {
public static void main(String[] args) {
// byte example
byte byteValue = 100; // Used for small numbers
System.out.println("Byte value: " + byteValue);
// short example
short shortValue = 15000; // Used for small integers
System.out.println("Short value: " + shortValue);
// int example
int intValue = 200000; // General-purpose integer
System.out.println("Int value: " + intValue);
// long example
long longValue = 3000000000L; // Used for large integers
System.out.println("Long value: " + longValue);
// float example
float floatValue = 10.5f; // Used for single-precision floating-point
System.out.println("Float value: " + floatValue);
// double example
double doubleValue = 20.99; // Used for double-precision floating-point
System.out.println("Double value: " + doubleValue);
// char example
char charValue = 'A'; // Used for single characters
System.out.println("Char value: " + charValue);
// boolean example
boolean booleanValue = true; // Used for true/false values
System.out.println("Boolean value: " + booleanValue);
}
}
Explanation:
- Each variable is initialized with a value that demonstrates its purpose.
- The
System.out.printlnstatements print the values to the console, showing how each data type can be used.
How to Run:
- Save the code in a file named
DataTypePurposeExample.java. - Compile it using:
javac DataTypePurposeExample.java - Run it using:
java DataTypePurposeExample
Expected Output:
Byte value: 100
Short value: 15000
Int value: 200000
Long value: 3000000000
Float value: 10.5
Double value: 20.99
Char value: A
Boolean value: true
If you have any further questions or need additional examples, feel free to ask!
