Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting default value for primitive types

I have a Java primitive type at hand:

Class<?> c = int.class; // or long.class, or boolean.class 

I'd like to get a default value for this class -- specifically, the value is assigned to fields of this type if they are not initialized. E.g., 0 for a number, false for a boolean.

Is there a generic way to do this? I tried this:

c.newInstance() 

But I'm getting an InstantiationException, and not a default instance.

like image 733
ripper234 Avatar asked May 23 '10 13:05

ripper234


People also ask

How do you write a Java program to display default value of all primitive data types in Java?

Remember, to get the default values, you do not need to assign values to the variable. static boolean val1; static double val2; static float val3; static int val4; static long val5; static String val6; Now to display the default values, you need to just print the variables.

What is the default value of short and char data type?

The minimum value char can hold is 'u0000' which is a Unicode value denoting 'null' or 0 in decimal. The maximum value it can hold is 'uffff' or 65,535 inclusive. The minimum value which is 'u0000' is also the default value of char.


2 Answers

The Guava Libraries already contains that:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Defaults.html

Calling defaultValue will return the default value for any primitive type (as specified by the JLS), and null for any other type.

Use it like so:

import com.google.common.base.Defaults; Defaults.defaultValue(Integer.TYPE); //will return 0 
like image 200
whiskeysierra Avatar answered Oct 14 '22 12:10

whiskeysierra


It's possible to get the default value of any type by creating an array of one element and retrieving its first value.

private static <T> T getDefaultValue(Class<T> clazz) {     return (T) Array.get(Array.newInstance(clazz, 1), 0); } 

This way there is not need to take account for every possible primitive type, at the usually negligible cost of creating a one-element array.

like image 33
Antag99 Avatar answered Oct 14 '22 14:10

Antag99