DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Avoiding If-Else: Advanced Approaches and Alternatives
  • Dust: Open-Source Actors for Java
  • Redefining Java Object Equality

Trending

  • Start Coding With Google Cloud Workstations
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  • Automatic Code Transformation With OpenRewrite
  1. DZone
  2. Data Engineering
  3. Data
  4. How to Write a C-like sizeof Function in Java

How to Write a C-like sizeof Function in Java

If you just started learning Java and come from a C background, this article is for you! Click here to read more about the difference between C and Java in relation to the sizeof function.

By 
Javin Paul user avatar
Javin Paul
·
Jun. 22, 18 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
38.7K Views

Join the DZone community and get the full member experience.

Join For Free

If you just started learning Java and come from C background, then you might have noticed a 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 a 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 the 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 the  sizeOf()  operator/function in 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? Doesn't it just need one 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 (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 four 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:


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 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 predefined size of Java data types, nor do you think about taking advantage of size constants defined in wrapper classes, e.g. Integer or Double. If you can come across any other way of finding the size of primitive data type then let us know.

Java (programming language) Data Types

Published at DZone with permission of Javin Paul, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Avoiding If-Else: Advanced Approaches and Alternatives
  • Dust: Open-Source Actors for Java
  • Redefining Java Object Equality

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!