Friday, 12 February 2016

Java Programming Tips and Best Practices for Beginners-Part3

11. How to time operations in Java
There are two standard ways to time operations in Java: System.currentTimeMillis() and System.nanoTime() The question is, which of these to choose and under what circumstances. In principle, they both perform the same action but are different in the following ways:
1. System.currentTimeMillis takes somewhere between 1/1000th of a second to 15/1000th of a second (depending on the system) but System.nanoTime() takes around 1/1000,000th of a second (1,000 nanos)
2. System.currentTimeMillis takes a few clock cycles to perform Read Operation. On the other hand, System.nanoTime() takes 100+ clock cycles.
3. System.currentTimeMillis reflects Absolute Time (Number of millis since 1 Jan 1970 00:00 (Epoch Time)) but System.nanoTime() does not necessarily represent any reference point.
12. Choice between Float and Double
Data type        Bytes used      Significant figures (decimal)
Float    4          7
Double 8          15
Double is often preferred over float in software where precision is important because of the following reasons:
Most processors take nearly the same amount of processing time to perform operations on Float and Double. Double offers far more precision in the same amount of computation time.
13. Computation of power
To compute power (^), java performs Exclusive OR (XOR). In order to compute power, Java offers two options:
1.         Multiplication:
1          double square = double a * double a;                            // Optimized
2          double cube = double a * double a * double a;                   // Non-optimized
3          double cube = double a * double square;                         // Optimized
4          double quad = double a * double a * double a * double a;            // Non-optimized
5          double quad = double square * double square;                    // Optimized
4.         pow(double base, double exponent):‘pow’ method is used to calculate where multiplication is not possible (base^exponent)
1          double cube = Math.pow(base, exponent);
Math. pow should be used ONLY when necessary. For example, exponent is a fractional value. That is because Math.pow() method is typically around 300-600 times slower than a multiplication.
14. How to handle Null Pointer Exceptions
Null Pointer Exceptions are quite common in Java. This exception occurs when we try to call a method on a Null Object Reference. For example,
1          int noOfStudents = school.listStudents().count;
If in the above example, if get a NullPointerException, then either school is null or listStudents() is Null. It’s a good idea to check Nulls early so that they can be eliminated.
1          private int getListOfStudents(File[] files) {
2                if (files == null)
3                  throw new NullPointerException("File list cannot be null");
4              }
15. Encode in JSON
JSON (JavaScript Object Notation) is syntax for storing and exchanging data. JSON is an easier-to-use alternative to XML. Json is becoming very popular over internet these days because of its properties and light weight. A normal data structure can be encoded into JSON and shared across web pages easily. Before beginning to write code, a JSON parser has to be installed. In below examples, we have used json.simple (https://code.google.com/p/json-simple/).
Below is a basic example of Encoding into JSON:
01        import org.json.simple.JSONObject;
02        import org.json.simple.JSONArray;
03       
04        public class JsonEncodeDemo {
05            
06            public static void main(String[] args) {
07                
08                JSONObject obj = new JSONObject();
09                obj.put("Novel Name", "Godaan");
10                obj.put("Author", "Munshi Premchand");
11         
12                JSONArray novelDetails = new JSONArray();
13                novelDetails.add("Language: Hindi");
14                novelDetails.add("Year of Publication: 1936");
15                novelDetails.add("Publisher: Lokmanya Press");
16                
17                obj.put("Novel Details", novelDetails);
18                
19                System.out.print(obj);
20            }
21        }
Output:

1          {"Novel Name":"Godaan","Novel Details":["Language: Hindi","Year of Publication: 1936","Publisher: Lokmanya Press"],"Author":"Munshi Premchand"}

No comments:

Post a Comment