Guava tips: Defaults and HttpHeaders

We’ll cover two tiny Guava classes today, which I’m sure will provoke a “ehm… nice to know, I guess?” from you! :-)

Defaults Link to heading

The simple Defaults class has only one method: defaultValue, which returns the “default value” given a Class:

  • for the primitives numeric data types (char, short, int, long, float, double) it will return 0;
  • for boolean it will return false;
  • for byte it will return (byte)0;
  • and for objects it will return null.

For example:

assertEquals(Long.valueOf(0L), Defaults.defaultValue(long.class));
assertEquals(false, Defaults.defaultValue(boolean.class));
assertEquals(null, Defaults.defaultValue(String.class));

HttpHeaders Link to heading

The tiny class HttpHeaders simply contains one constant for each of the standard HTTP headers. Nothing more, nothing less. It’s better than rolling the constant in your code, I suppose.