Java Code Examples: Variables and Types

Principles

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

Primitive Types and Literals

byte

// use hex value
byte num1 = (byte) 0x7F; // 127
// use int
byte num3 = (byte) 127;
// use string
byte num2 = new Byte("127"); // 127

byte array

// use hex values
byte[] byteArray1 = new byte[]{(byte) 0xE2, (byte) 0x98, (byte) 0x83};
// use byte values
byte[] byteArray2 = new byte[]{(byte) -30, (byte) -104, (byte) -125};
// use int values
byte[] byteArray3 = new byte[]{(byte) 226, (byte) 152, (byte) 131};
System.out.println(Arrays.toString(byteArray1)); // [-30, -104, -125]
System.out.println(Arrays.toString(byteArray2)); // [-30, -104, -125]
System.out.println(Arrays.toString(byteArray3)); // [-30, -104, -125]

Initialize variables

  • Initialize Primitive type variables
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
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;
// objects
Object object = new Object();
  • Initialize List variables
List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3));
  • Initialize Set variables
// 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
// 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
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
public static final String str = "hello";
public static final int[] MY_ARRAY = {1, 2, 3};
  • Initialize List constants
public static final List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3));
  • Initialize Set constants
public static final Set<Integer> SET = new HashSet();
static {
SET.add(1);
SET.add(2);
}
  • Initialize Map constants
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
// 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
// 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
// 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.
public enum WeekDay {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
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

// 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

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

Date formatting

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

String formatting

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,

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.

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