Friday, September 15, 2023

How to find size, Default, Maximum and Minimum values of Primitive Data Types in Java? Example Tutorial

Well, this is absolute beginner post in Java and Why I am writing this? because of a question, which actually confused me? Do you know what is the size of boolean variable in Java? Does it take 1 byte(8 bits) or just 1 bit? My memory was saying 1 byte but my logic was saying 1 bit, because it only holds two values, true and false, which can be represented by using 1 bit, by 0 and 1. This make me to go back to my core Java book and recall all default values. By the way, you don't need to go book always, as you can check default value, maximum and minimum of any data-type by running a Java programe and printing there value.

Only information, which I don't know you can get is size of any variable from Java program e.g. how to find size of int primitive in Java? I know it take 32 bit or 4 bytes, but how exactly do you know that without looking at online Java documentation or referring any book? any Idea? Ahh, did I say writing improves your thinking process? 

While writing this one idea struck me, we can count bits in Java right? so by counting bit on any variable, we can definitely know it's size. Since size of a primitive data type is equal to number of bits it have, What do you think? is it possible? let me know your answer. 

Unfortunately Java doesn't have C like sizeOf() operator, but until you remember it you don't really need it, because Java is platform independent and so is size of primitive data types. An int variable will always take 4 bytes or 32 bit, on all platform e.g. Windows XP, Windows 8, Mac, Linux or Ubuntu.

Now to answer the question, I raised in first paragraph, size of boolean is mystery in Java? mystery??? Yes, size of boolean is virtual machine dependent, one VM can take 1 byte other may take few more bytes to represent a boolean variable. 

Now this may raise question about Java being platform dependent, but that's only about size of boolean variable, not the size of class file. Size of class file is always constant in Java. Since we can only use boolean variable inside a class, there is no risk of platform dependency. 

Finally, here is the size of all primitive types in Java :

byte - 8 bits or 1 byte
char - 16 bits or 2 bytes
short - 16 bits or 2 bytes
int - 32 bits or 4 bytes
long - 64 bits or 8 bytes
float - 32 bits or 4 bytes
double - 64 bits or 8 bytes
boolean - This data type represents one bit of information, but its "size" isn't something that's precisely defined.


Now, you know the size of each primitive types in Java (except boolean), one more information, which is equally important is whether a particular type is signed or unsigned. If a type is signed, which means 1 bit is used to represent sign i.e. 0 for positive numbers and 1 for negative numbers. 

Which also means that they have 1 less bit to store information, which eventually affect their maximum value. Except char, all numeric types are signed, which means char has all 16 bits to store numbers but short has only 15 bits to store data, and one bit to store sign. 

This also implies that char cannot be negative, it can only be positive or zero and its maximum value should also be greater than short, which is the case and we will see in detail in next few section.




Default values of primitive Data types in Java

Now let's understand default values of primitive data types. When a variable is created but not initialized, the value it holds is called default value of that primitive type. For example, default value of boolean is false, default value of int variable is zero, default value of float variable is 0.0 and default values of reference data type is always null .

By the way it's easy to find default values of any primitive data types in Java, just create variable and print its value, but, you cannot do it inside any method, because variable declared inside Java methods are local variable and they must have to be explicitly initialized before use. 

Java compiler will throw compile time error related to uninitialized variable as shown below :

public static void defaultValue(){
    boolean bool;
    System.out.println("Default value of boolean variable in Java is : " + bool);
}

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
        The local variable bool may not have been initialized


So, how do you print default values of primitive data types in Java? answer is simple, declare them as member variable and print there default values, as shown in following example :

/**
 * Java Program to print default values of primitive and reference data types.
 *
 * @author Javin
 */
public class DefaultValuePrinter {
    // primitive data types in Java
    private static byte iMByte;
    private static short iMShort;
    private static char iMChar;
    private static int iMInt;
    private static long iMLong;
    private static float iMFloat;
    private static double iMDouble;
    private static boolean iMBoolean;
    // reference data type in Java
    private static Object iMObject;
    public static void main(String args[]) {
        // printing default value of primitive type in Java          
        System.out.println("Default value of byte variable in Java is : " + iMByte);
        System.out.println("Default value of short variable in Java is : " + iMShort);
        System.out.println("Default value of char variable in Java is : " + iMChar);
        System.out.println("Default value of int variable in Java is : " + iMInt);
        System.out.println("Default value of long variable in Java is : " + iMLong);
        System.out.println("Default value of float variable in Java is : " + iMFloat);
        System.out.println("Default value of double variable in Java is : " + iMDouble);
        System.out.println("Default value of boolean variable in Java is : " + iMBoolean);
        // printing default value of reference type in Java
        System.out.println("Default value of reference variable in Java is : " + iMObject);
    }
}


Output
Default value of byte variable in Java is : 0
Default value of short variable in Java is : 0
Default value of char variable in Java is :
Default value of int variable in Java is : 0
Default value of long variable in Java is : 0
Default value of float variable in Java is : 0.0
Default value of double variable in Java is : 0.0
Default value of boolean variable in Java is : false
Default value of reference variable in Java is : null

Well, all output are expected, int got default value zero, boolean has default value false, floating point numbers e.g. float and double has default value 0.0 and reference type has default value null, except one interesting point, what is the default value of char? 

When I printed default value of char, it actually prints a little square in console, but when I copied it doesn't get copied, in fact I had to copy rest of lines by excluding that character? Do you know what was that? It was Unicode char '\u0000'.


What is Maximum and Minimum values of Primitive data types in Java?

Now let's see what is maximum and minimum values of primitive data types in Java, and how can you derive that by knowing size of primitive data type. Let's start with smallest numeric data type, byte. Total size of byte variable is 8 bit, out of 1 bit is used for sign, which means we only have 7 bits to store data. 

Since maximum value of a bit is 1 and minimum is 0, if we set all 7 bits in a byte variable, we will get something like 01111111, where first zero is sign bit and used to denote positive number. This is equivalent to decimal 127. 

In simple terms its value of 2^7 - 1. So maximum value of byte is 127 or 2^7-1. Now minimum value of byte is all 11111111 which is (-128) because byte is a signed two's complement integer value. 

So minimum and maximum value of byte variable in Java is -128 and 127. Since character is unsigned, all 16 bits are used to stored data, which means its maximum value is 2^16 - 1 i.e. 65535 and minimum value is 0. Similarly maximum and minimum value of short variable in Java is 32767 and -32768.  

Float and Double can represent very large number, because they use exponentials. Following program will print maximum and minimum values of all primitive data types in Java :


/**
 * Java Program to print maximum and minimum values of primitive data types.
 *
 * @author
 */
public class MaxMinPrinter {
    public static void main(String args[]) {
        // printing maximum and minimum value of primitive data types in Java
System.out.printf("Maximum and minimum value of byte in Java is %s and %s %n",
                Byte.MAX_VALUE, Byte.MIN_VALUE);
System.out.printf("Maximum and minimum value of short in Java is %s and %s %n",
                Short.MAX_VALUE, Short.MIN_VALUE);
System.out.printf("Maximum and minimum value of char in Java is %d and %d %n",
                (int) Character.MAX_VALUE, (int) Character.MIN_VALUE);
System.out.printf("Maximum and minimum value of int variable in Java is %s and %s %n",
                Integer.MAX_VALUE, Integer.MIN_VALUE);
ystem.out.printf("Maximum and minimum value of long variable in Java is %s and %s %n",
                Long.MAX_VALUE, Long.MIN_VALUE);
System.out.printf("Maximum and minimum value of float variable in Java is %s and %s %n",
                Float.MAX_VALUE, Float.MIN_VALUE);
System.out.printf("Maximum and minimum value of double in Java is %s and %s %n",
                Double.MAX_VALUE, Double.MIN_VALUE);
    }
}


Output:
Maximum and minimum value of byte in Java is 127 and -128
Maximum and minimum value of short in Java is 32767 and -32768
Maximum and minimum value of char in Java is 65535 and 0
Maximum and minimum value of int variable in Java is 2147483647 and -2147483648
Maximum and minimum value of long variable in Java is 9223372036854775807 and -9223372036854775808
Maximum and minimum value of float variable in Java is 3.4028235E38 and 1.4E-45
Maximum and minimum value of double in Java is 1.7976931348623157E308 and 4.9E-324



Interesting things about primitive data types in Java 

1) While assigning value to long variable I was just typing 3 and I hit by this number long iMLong = 33333333333; at this number Eclipse keeps giving me number and I am getting confused that how come long be so short, I would say it’s either my fault or Eclipse being too smart. 

Eclipse was treating this number as int, because by default all non-floating numbers are int in Java, and this is certainly out of range for an int variable, but not for long. 

So how do I tell Eclipse that this is a long variable and not a int one? by using suffix L or l. 

I prefer to use capital case L, because it’s more obvious, while lower case just look like numeric digit 1, can you differentiate between them by naked eye? tell me which one is numeric one? 1 or l?

Same thing can happen with float variable, because by default all floating point numbers are treated as double in Java. To tell Java compiler or Eclipse IDE or whatever IDE you are using, that it’s a float variable, use suffix f or F, again going by convention you should use F. 

Now you can ask me which convention? well it's called convention of consistency :), Since we have used L with long, we should use F with float. Always remember, floating point in Java are by default double and complete numbers are by default int primitive.

2) Size of data types are also platform independent in Java. What does this mean? It means your int variable will take 4 bytes in both Windows and Linux. Similarly double will take 8 bytes in both 32-bit machine and 64-bit machine, and your char will take 2 bytes in both Mac and Windows.

3) Default value of char primitive data type is Unicode '\u0000', when I printed it on machine in Eclipse console, it printed a little square. In order to get numeric value, just cast that into int and it will print zero.

4) All numeric primitive types e.g. byte, short, char, int, long, float and double has their equivalent wrapper classes e.g. java.lang.Byte, java.lang.Short, java.lang.Character, java.lang.Integer, java.lang.Long, java.lang.Float and java.lang.Double. 

From JDK 1.5 onward, Java atomically converts primitive to wrapper and this is known as autoboxing in Java. Similarly it also automatically converts a wrapper class into primitive value, and this is known as unboxing. 

This automatic conversion happens based on context e.g. if you pass a wrapper object to a method accepting primitive value, Java will unbox wrapper value into primitive type and vice-versa.

5) All numeric wrapper class holds size, maximum and minimum value of their primitive data type counterpart, defined as following constants. This values are from java.lang.Byte class

public static final byte        MAX_VALUE       127
public static final byte        MIN_VALUE       -128
public static final int SIZE    8


6) If your Eclipse prints maximum and minimum value of Character as ? and little square like below then

Maximum and minimum value of char in Java is ? and [], then cast them into int before displaying as we have done in our example.

7) Since boolean can only represent two values, there is no question of maximum and minimum values of boolean variable in Java.

Now, Here are few tables with important information about primate types in Java

Data type and their Size





Data type and Default value





Data type and Maximum, Minimum value







That's all about default value, size and maximum and minimum values of primitive data types in Java. Now we know that size of boolean varies between JVM, character is unsigned and  one should use suffix like F or L to represent float and long data types, because by default full numbers are of integer type and floating point numbers are double data type. 

We also learned that default value of reference type is null. Let me know if you have any question related to size, default value, and maximum minimum range of primitive data types in Java.

Now, one question for you, which is your favorite Java data type?

2 comments:

  1. My favorit edata type is int and String, those are the ones I most used them.

    ReplyDelete
  2. My favorit edata type is int and String, those are the ones I most used them.

    ReplyDelete