Wednesday, June 20, 2018

How to write a C like Sizeof function in Java

If you have just started learning Java and came from C background then you might have noticed some difference between Java and C programming language e.g. String is an object in Java and not a NULL terminated character array. Similarly, there is is no sizeof() operator in Java. All primitive values have predefined size e.g. int is 4 bytes, char is 2 byte, short is 2 byte, long and float is 8 byte and so on. But if you are missing sizeOf operator then why not let's make it a coding task? If you are Ok, then your next task is to write a method in Java, which can behave like sizeOf() operator/function of C and returns size in bytes for each numeric primitive types i.e. all primitive types except boolean.

Many of you think, why we are not including boolean? isn't that it just need 1 bit to represent true and false value? Well, I am nog including boolean in this exercise because the size of boolean is not strictly defined in Java specification and varies between different JVM (See Java Fundamentals: The Java Language).

Also, for your knowledge, size of primitives in Java is fixed, it doesn't depend upon the platform.
So an int primitive variable will take 4 bytes in both Windows and Linux, both on 32-bit and 64-bit machines.

Anyway, here is the size and default values of different primitive types in Java for your reference:

How to write a C like Sizeof function in Java



Now it's up to your creativity to give multiple answers, but we need at least one answer to solve this coding problem.  If you guys will like this problem then I might include this on my list of 75 Coding Problems to Crack Any Programming Job interview, drop a note if this is interesting and challenging.


Java sizeof() function Example

Here is our complete Java program to implement sizeof operator. It's not exactly size but its purpose is same. sizeof returns how much memory a particular data type take and this method does exactly that.


/**
 * Java Program to print size of primitive data types e.g. byte, int, short, double, float
 * char, short etc, in a method like C programming language's sizeof
 *
 * @author Javin Paul
 */
public class SizeOf{

    public static void main(String args[]) {

        System.out.println(" size of byte in Java is (in bytes) :  "
    + sizeof(byte.class));
        System.out.println(" size of short in Java is (in bytes) :" 
    + sizeof(short.class));
        System.out.println(" size of char in Java is (in bytes) :" 
    + sizeof(char.class));
        System.out.println(" size of int in Java is (in bytes) :" 
    + sizeof(int.class));
        System.out.println(" size of long in Java is (in bytes) :" 
    + sizeof(long.class));
        System.out.println(" size of float in Java is (in bytes) :" 
    + sizeof(float.class));
        System.out.println(" size of double in Java is (in bytes) :" 
    + sizeof(double.class));

    }


    /*
     * Java method to return size of primitive data type based on hard coded values
     * valid but provided by developer
     */
    public static int sizeof(Class dataType) {
        if (dataType == null) {
            throw new NullPointerException();
        }
        if (dataType == byte.class || dataType == Byte.class) {
            return 1;
        }
        if (dataType == short.class || dataType == Short.class) {
            return 2;
        }
        if (dataType == char.class || dataType == Character.class) {
            return 2;
        }
        if (dataType == int.class || dataType == Integer.class) {
            return 4;
        }
        if (dataType == long.class || dataType == Long.class) {
            return 8;
        }
        if (dataType == float.class || dataType == Float.class) {
            return 4;
        }
        if (dataType == double.class || dataType == Double.class) {
            return 8;
        }
        return 4; // default for 32-bit memory pointer
    }


    /*
     * A perfect way of creating confusing method name, sizeof and sizeOf
     * this method take advantage of SIZE constant from wrapper class
     */
    public static int sizeOf(Class dataType) {
        if (dataType == null) {
            throw new NullPointerException();
        }
        if (dataType == byte.class || dataType == Byte.class) {
            return Byte.SIZE;
        }
        if (dataType == short.class || dataType == Short.class) {
            return Short.SIZE;
        }
        if (dataType == char.class || dataType == Character.class) {
            return Character.SIZE;
        }
        if (dataType == int.class || dataType == Integer.class) {
            return Integer.SIZE;
        }
        if (dataType == long.class || dataType == Long.class) {
            return Long.SIZE;
        }
        if (dataType == float.class || dataType == Float.class) {
            return Float.SIZE;
        }
        if (dataType == double.class || dataType == Double.class) {
            return Double.SIZE;
        }
        return 4; // default for 32-bit memory pointer
    }
}

Output:
size of byte in Java is (in bytes) :  1
size of short in Java is (in bytes) :2
size of char in Java is (in bytes) :2
size of int in Java is (in bytes) :4
size of long in Java is (in bytes) :8
size of float in Java is (in bytes) :4
size of double in Java is (in bytes) :8


That's all in this programming exercise of writing a sizeof like a method in Java. This is actually tricky because, you don't think of taking advantage of the pre-defined size of Java data types, neither you think about taking advantage of SIZE constants defined in wrapper classes e.g. Integer or Double. Well, if you can come across any other way of finding the size of primitive data type then let us know.

Further Learning
The Complete Java MasterClass
Java Fundamentals: The Java Language
Data Structures and Algorithms: Deep Dive Using Java

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.


No comments :

Post a Comment