Contents
  1. 1. Initialize variables
  2. 2. Initialize constants
  3. 3. Initialize Immutable Container
  4. 4. Enumeration Type vs Constants
  5. 5. Type Formatting
  6. 6. Value Comparison
  7. 7. References

Principles

  • Member Variables of classes should use wrapper types for nullable. E.g. Integer, Long.

Initialize variables

  • Initialize Primitive type variables
1
2
3
4
5
6
7
8
byte byteVal = 1;
short shortVal = 1;
int intVal = 1;
long longVal = 1L;
float floatVal = 1.0F;
double doubleVal = 1.0;
boolean booleanVal = true;
char charVal = 'a';
  • Initialize Strings and array variables
1
2
3
4
5
6
7
String str = "hello";
int[] array = {1, 2, 3};
int[] array2 = new int[]{1, 2, 3};
int[] array3 = new int[3];
array3[0] = 1;
array3[1] = 2;
array3[2] = 3;
1
2
// objects
Object object = new Object();
  • Initialize List variables
1
List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3));
  • Initialize Set variables
1
2
3
4
5
6
7
8
9
10
11
12
// Using Another Collection Instance
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));

// Using Anonymous Class
Set<Integer> set = new HashSet() {{
add(1);
add(2);
}};

// Using Stream Since Java 8
Set<String> set3 = Stream.of("a", "b", "c")
.collect(Collectors.toCollection(HashSet::new));
  • Initialize Maps variables
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Using Anonymous Class (Not recommend, Double Brace Initialization should not be used. Replace of to use map.put(key, value).)
Map<Integer, String> map = new HashMap<Integer, String>() {{
put(1, "one");
put(2, "two");
put(3, "three");
}};

// Using Stream Since Java 8
Map<String, Integer> map2 = Stream.of(new Object[][] {
{ "key1", 1 },
{ "key2", 2 },
}).collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));

// Using a Stream of Map.Entry
Map<String, Integer> map3 = Stream.of(
new AbstractMap.SimpleEntry<>("key1", 1),
new AbstractMap.SimpleEntry<>("key2", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Initialize constants

  • Initialize Primitive type constants
1
2
3
4
5
6
7
8
public static final byte byteVal = 1;
public static final short shortVal = 1;
public static final int intVal = 1;
public static final long longVal = 1L;
public static final float floatVal = 1.0F;
public static final double doubleVal = 1.0;
public static final boolean booleanVal = true;
public static final char charVal = 'a';
  • Initialize Strings and Array constants
1
2
public static final String str = "hello";
public static final int[] MY_ARRAY = {1, 2, 3};
  • Initialize List constants
1
public static final List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3));
  • Initialize Set constants
1
2
3
4
5
public static final Set<Integer> SET = new HashSet();
static {
SET.add(1);
SET.add(2);
}
  • Initialize Map constants
1
2
3
4
5
6
public static final Map<Integer, String> MAP = new HashMap<Integer, String>();
static {
MAP.put(1, "one");
MAP.put(2, "two");
MAP.put(3, "three");
}

Initialize Immutable Container

  • Initialize Immutable List
1
2
3
4
5
// JDK 8 (Don't expose internal_list reference of unmodifiableList(List internale_list)). Arrays.asList() can't increase size, but it can modify its elements.
public static final List UNMODIFY_LIST = Collections.unmodifiableList(Arrays.asList(1, 2, 3));

// JDK 9 (Recommend, less space cost)
public static final List stringList = List.of("a", "b", "c");
  • Initialize Immutable Set
1
2
3
4
5
// JDK 8
public static final Set<String> stringSet = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("a", "b", "c")));

// JDK 9 (Recommend)
public static final Set<String> stringSet2 = Set.of("a", "b", "c");
  • Initialize Immutable Map
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Immutable Map, JDK 8
public static final Map<Integer, String> UNMODIFY_MAP = Collections.unmodifiableMap(
new HashMap<Integer, String>()
{
{
put(1, "one");
put(2, "two");
put(3, "three");
};
});

// java 9, return ImmutableCollections (Recommend)
public static final Map<Integer, String> my_map2 = Map.of(1, "one", 2, "two");

// java 10, return ImmutableCollections (Recommend)
public static final Map<Integer, String> my_map3 = Map.ofEntries(
entry(1, "One"),
entry(2, "two"),
entry(3, "three"));

Enumeration Type vs Constants

  • If number of a set of constant is fixed, you should use enum type.
  • If number of a set of constant is increasing and variable, you should use constant variables.
1
2
3
4
5
6
7
8
9
public enum WeekDay {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
1
2
3
4
5
6
7
public static final int MONDAY = 0;
public static final int TUESDAY = 1;
public static final int WEDNESDAY = 2;
public static final int THURSDAY = 3;
public static final int FRIDAY = 4;
public static final int SATURDAY = 5;
public static final int SUNDAY = 6;

Type Formatting

Integer formatting

1
2
3
4
5
6
// Specifying length. 
String str2 = String.format("|%10d|", 101); // | 101|
// Left-justifying within the specified width.
String str3 = String.format("|%-10d|", 101); // |101 |
// Filling with zeroes.
String str4 = String.format("|%010d|", 101); // |0000000101|

Double formatting

1
2
Double value = 9.999;
String result = new DecimalFormat("#0.00").format(value);
1
2
3
double value = 3.1415926;
String result = String.format("value is: %.2f", value);
System.out.println(result); // value is: 3.14

Date formatting

1
2
Date date = new Date();
String result = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

String formatting

1
2
3
4
5
String s = String.format("name is %s", name);
// Specify Maximum Number of Characters
String.format("|%.5s|", "Hello World"); // |Hello|
// Fill with zeros
String.format("%32s", Integer.toBinaryString(value)).replace(' ', '0')

If the template string contain %, you need replace with %%. For example,

1
2
String.format("%s increase 7%%", "Stock"); // Stock increase 7%
String.format("name like '%%%s%%'", "Jack"); // name like '%Jack%'

Value Comparison

Wrapper Object Comparison

Value type: 1. cache value(Integer: -128~127). 2. non-cache value. 3. null value.

1
2
3
4
Integer a = null; // 1, 128, null
Integer b = null; // 1, 128, null
boolean doesEqual = (a != null && a.equals(b)) || a == b;
System.out.println(doesEqual);

References

[1] Initialize a HashMap in Java

Contents
  1. 1. Initialize variables
  2. 2. Initialize constants
  3. 3. Initialize Immutable Container
  4. 4. Enumeration Type vs Constants
  5. 5. Type Formatting
  6. 6. Value Comparison
  7. 7. References