call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
Java best practices
1. JAVA best practices
● Avoid magic numbers, use private static final (constants)
● Avoid double negatives, e.g. if(!notFound())
● Don’t put constants in interfaces use import static instead
● Use enums not constants
● Don’t do string concatenation in a loop
● Never make an instance fields of class public . Use private field +
GETTER_FUNCTION() and SETTER_FUNCTION()
2. Try to use Primitive types instead of Wrapper class
● Wrapper classes are great. But at same time they are slow.
● Primitive types are just values, whereas Wrapper classes are stores
information about complete class.
int x = 10;
Integer x1 = new Integer(10);
● Also if you are using a wrapper class object then never forget to initialize it to
a default value(null).
JAVA best practices
3. JAVA best practices
Avoid creating unnecessary objects and always prefer to do Lazy initialization. Initialize only when
required
public class Countries {
private List countries;
public List getCountries() {
if(null == countries) {
countries = new ArrayList();
}
return countries;
}
}
4. Abstract classes compared to interfaces
You cannot instantiate them, and they may contain a mix of methods declared with or without an
implementation.
The only methods that have implementations in interfaces are default and static methods.
In interfaces all fields are automatically public, static, and final, and all methods that declared or
defined (as default methods) are public
In abstract classes fields can be not static and final, and concrete methods can be public, protected,
and private.
You can extend only one class, whether or not it is abstract, whereas you can implement any number
of interfaces
5. When use?
abstract class
o You want to share code among several closely related classes.
o You expect that classes that extend your abstract class have many common methods or fields, or require
access modifiers other than public (such as protected and private).
o You want to declare non-static or non-final fields. This enables you to define methods that can access and
modify the state of the object to which they belong.
interface
o You expect that unrelated classes would implement your interface.
o You want to specify the behavior of a particular data type, but not concerned about who implements its
behavior.
6. Switch or If
A switch works with the byte, short, char, and int primitive data types. It also works with enumerated
types (discussed in Enum Types), the String class(in Java SE 7 and later), and a few special classes
that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and
Strings).
If the number of switch labels is N, a chain of ifs takes O(N) to dispatch, while a switch always
dispatches in O(1). This is how it is done: compiler places addresses of switch labels into an array,
computes an index based on the label values, and performs a jump directly, without comparing the
switch expression to value one by one. In case of strings used as switch labels, the compiler produces
a hash table, which looks up an address in O(1) as well.
7. Loop optimization
At first set the length in variable then use that variable
for(int i = 0; i < ob.length();++i){
// some code
}
int length = ob.length();
for(int i = 0; i < length;++i){
// some code
}
8. Loop optimization
● The loop can be improved even more by changing the loop to count backwards. The JVM is
optimized to compare to integers between -1 and +5. So rewriting a loop to compare against 0
will produce faster loops. So for example, the loop on the right could be changed to use the
following for loop instruction: for (int j = len-1; j >= 0; j—)
● Once the processing requirement of a loop has been completed, use the break statement to
terminate the loop. This saves the JVM from iterating through the loop doing the evaluations of
the termination criteria.
9. Loop optimization
If a computation produces the same value in every loop iteration, move it out of the loop
for i = 1 to N {
Integer x = 100*N + 10*i
}
var1 = 100*N
for i = 1 to N {
Integer x = var1 + 10* i
}
10. Collections
1. Set
● No particular order
● There are two libraries for set collections HashSet and TreeSet.HashSet is faster than TreeSet because TreeSet
provides iteration of the keys in order
1. List
● Linear manner. (An array is an example of a list where objects are stored into the list based upon the data
structure’s index.)
● There are 4 classes included in a list: ArayList, Vector, Stack, LinkedList(each Node consists of a value, prev
and next pointers)
● ArrayList is the fastest
● Vector is slower because of synchronization
11. Collections
3. Map
● Paired structure key value retrieved by key
● There are 3 classes included in map collection: HashMap, HashTable, TreeMap,
● Using for searching when you want to retrieve an object
● HashTables and HashMaps are fast
Unlike the Vector collection class, ArrayLists and HashMaps are not synchronized classes. When using multithreaded
applications use ArrayLists and HashMaps to improve performance when synchronized access to the data is not a
concern.
You should always declare your variable as a List so that the implementation can be changed later as needed.
12. NullPointerException
● Avoid returning null from method, instead return empty collection or empty array. By returning
empty collection or empty array you make sure that basic calls like size(), length() doesn't fail
with NullPointerException.
● Never call .equals(null) equals is a method, if you try to invoke it on a null reference, you'll get a
NullPointerException.
● Call equals() and equalsIgnoreCase() methods on known String literal rather unknown object
Object unknownObj = null
if(“str”.equals(unknownObj)){
System.out.println(“better way”);
}
● Use StringUtils.isBlank(), isNumeric(), isWhiteSpace(), isEmpty() methods
13. Modify Strings with StringBuilder
String objects are immutable.
● You may think you’re changing a String, but you’re actually creating a new object.
● Danger of OutOfMemoryErrors.
● Poor performance.
StringBuilder is mutable.
● All changes are to the same object.