20 java best practices

Nour Krichene
5 min readMar 8, 2023

Some of java best practices that will help you enhance your code’s quality.

20 java best practices

1-Favor primitives over primitive wrappers whenever possible.

Long idNumber;
long idNumber; // long takes less memory than Long

2-To check for oddity of a number the bitwise AND operator is much faster than the arithmetic modulo operator.

public boolean isOdd(int num) {
return (num & 1) != 0;
}
// best way to check the oddity of a number

3-Avoid redundant initialization (0, false, null..)
Do not initialize variables with their default initialization, for example, a boolean by default has the value false so it is redundant to initialize it with the false value.

String name = null; // redundant
int speed = 0; // redundant
boolean isOpen = false; // redundant


String name;
int speed;
boolean isOpen;
// same values in a cleaner way

4-Declare class members private wherever possible and always give the most restricted access modifier.

public int age; // very bad
int age; // bad
private int age; // good

5-Avoid the use of the ‘new’ keyword while creating String

String s1 = new String("AnyString") ; 
// low instantiation
// The constructor creates a new object, and adds the literal…

--

--