Wednesday, May 10, 2023

How to write a C like sizeof() function in Java? [Solved]

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 job is to write a method in Java, which can behave like sizeOf() operator/function of C and returns the size in bytes for each primitive numeric type, 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, the 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.

Also, basic knowledge of essential data structure and algorithms is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to improve your knowledge and algorithms skills.

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 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 the sizeof operator. It's not exactly the size, but its purpose is the same. sizeof returns how much memory a particular data type takes, 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
Coursera's Data Structure & Algorithms Specialization
Data Structures and Algorithms: Deep Dive Using Java


Other Coding Interview Questions you may like
  • Print duplicate characters from String? (solution)
  • 10 Data Structure and Algorithms courses for Interviews (courses)
  • Reverse String in Java using Iteration and Recursion? (solution)
  • 20+ Array-based Coding Problems for interviews (questions)
  • Count the number of vowels and consonants in a String? (solution)
  • 7 Best Courses to learn Data Structure and Algorithms (courses)
  • Find duplicate characters in a String? (solution)
  • 10 Courses to learn Java Programming for Beginners (courses)
  • Count the occurrence of a given character in String? (solution)
  • My favorite free course to learn Data Structure and Algorithms (courses)
  • Convert numeric string to an int? (solution)
  • 50+ Data Structure and Algorithms Interview Questions (list)
  • Check if String is Palindrome? (solution)
  • 10 Books to learn Data Structure and Algorithms (books)
  • Find the highest occurred character in a String? (solution)
  • Check if a String contains only digits?  (solution)
  • 10 Data Structure, Algorithms, and Programming courses for interviews (courses)
  • Find the first non-repeated character from String? (solution)
  • Reverse words in a sentence without using a library method? (solution)
  • Reverse a String in place in Java? (solution)

Thanks for reading this article so far. If you like this coding or algorithm interview question and my explanation then please share it with your friends and colleagues. If you have any doubts or feedback then please drop a note.

P.S. - If you are preparing for Programming Job Interview and you need more such questions, can check the Data Structures and Algorithms Bootcamp by Jonathan Rasmusson course on  Udemy.

1 comment: