Can you provide code examples?

QuestionsQuestions8 SkillsProYour First Java LabSep, 30 2025
0129

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.println statements print the values to the console, showing how each data type can be used.

How to Run:

  1. Save the code in a file named DataTypePurposeExample.java.
  2. Compile it using: javac DataTypePurposeExample.java
  3. 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!

0 Comments

no data
Be the first to share your comment!