How to get the number of bytes of a variable in Java

1 Answer

0 votes
class Main {
    public static void main(String[] args) {
        int i = 42;
        System.out.println("Bytes of int: " + bytes(i));
        
        Integer I = 97;
        System.out.println("Bytes of Integer: " + bytes(I));
        
        boolean b = true;
        System.out.println("Bytes of boolean: " + bytes(b));
        
        char ch = 'a';
        System.out.println("Bytes of char: " + bytes(ch));
        
        float f = 13.9f;
        System.out.println("Bytes of flaot: " + bytes(f));
        
        long l = 172890;
        System.out.println("Bytes of long: " + bytes(f));
        
        double d = 3.14;
        System.out.println("Bytes of double: " + bytes(d));
    }

    public static <T> int bytes(T t) {
        return switch (t) {
            case Boolean b -> 1;
            case Byte b -> Byte.BYTES;
            case Short s -> Short.BYTES;
            case Character c -> Character.BYTES;
            case Integer i -> Integer.BYTES;
            case Float f -> Float.BYTES;
            case Long l -> Long.BYTES;
            case Double d -> Double.BYTES;
            default -> -1;
        };
    }
}


/*
run:

Bytes of int: 4
Bytes of Integer: 4
Bytes of boolean: 1
Bytes of char: 2
Bytes of flaot: 4
Bytes of long: 4
Bytes of double: 8

*/

 



answered Jun 4, 2025 by avibootz

Related questions

1 answer 88 views
1 answer 92 views
1 answer 176 views
1 answer 147 views
1 answer 63 views
1 answer 132 views
...