Home » Java » Core Java » How to write a C like Sizeof function in Java

About Javin Paul

Javin Paul
I have been working in Java, FIX Tutorial and Tibco RV messaging technology from past 7 years. I am interested in writing and meeting people, reading and learning about new subjects.

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 not including Boolean in this exercise because the size of boolean is not strictly defined in Java specification and varies between different JVM.

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:

sizeof

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.

Published on Java Code Geeks with permission by Javin Paul, partner at our JCG program. See the original article here: How to write a C like Sizeof function in Java

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
2 Comments Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Sachin Petkar Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Sachin Petkar
Guest
javaconstructor

Was the second method (sizeOf) actually tested on multiple platforms (32- vs 64-bit) and operating systems (Windows 10 vs Linux vs…) ?

A simple test run with JDK 1.8 on Windows 10 shows the sizes to be 8x of the ‘expected’ results.

Sachin Petkar
Guest
javaconstructor

In the sizeOf method, the “SIZE” constant returns the number of bits. What should be used instead to get the expected result is the “BYTES” constant, which returns the number of bytes.