Created
January 5, 2011 13:42
-
-
Save vaclavbohac/766321 to your computer and use it in GitHub Desktop.
This program prints sizes in bytes of primitive types in java.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Vaclav Bohac | |
* This program shows size of memory allocated by | |
* JVM for primitive types. | |
*/ | |
import java.lang.reflect.Field; | |
public class sizes { | |
/** | |
* Size of the single byte in bits. | |
*/ | |
public static final int BYTESIZE = 8; | |
/** | |
* Returns the size in bytes. | |
* @param int size of the type in bits | |
* @return int | |
*/ | |
public static int byteSize(int size) | |
{ | |
return size / BYTESIZE; | |
} | |
/** | |
* Makes print statement much shorter. | |
* @param string s string to print | |
* @param boolean[] print to error output | |
* @return void | |
*/ | |
public static void print(String s, boolean... error) | |
{ | |
if (error.length > 0 && error[0] == true) { | |
System.err.println(s); | |
return; | |
} | |
System.out.println(s); | |
} | |
public static void main(String[] args) | |
{ | |
print("Sizes of primitive types in bytes:"); | |
String[] names = { | |
"java.lang.Integer", | |
"java.lang.Long", | |
"java.lang.Short", | |
"java.lang.Float", | |
"java.lang.Double", | |
"java.lang.Character" | |
}; | |
try { | |
for (int i = 0, length = names.length, size = 0; i < length; i += 1) { | |
Class c = Class.forName(names[i]); | |
Field f = c.getField("SIZE"); | |
size = byteSize(f.getInt(f)); | |
print(names[i] + ": " + Integer.toString(size)); | |
} | |
} catch (Exception e) { | |
print(e.getMessage(), true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment