Few basics of java to remember while coding
Posted by Jai on October 10, 2012
I remember sometimes making such silly mistakes while coding in java. Here is a small list of things to keep remember while coding. The list was compiled long back but may be worth to revisit and may help someone.
- Java defines default initial values only for fields, and not for local variables – To avoid initializing fields to default values, is redundant.
- If super or this are called, they can only be called on the first line of the constructor. Constructors should never call an overridable method (an overridable method is one which is neither private, static, nor final). Constructors are never synchronized.
- Overloading – The signature of a method includes its name and the ordered list of its argument types. All other items appearing in a method header, such as exceptions, return type, final, and synchronized, do not contribute to a method’s signature.
- Compile regular expressions once. Pattern objects compile the regular expressions which are passed to them. If a regular expression is used many times, then this compilation should be performed only once.
- Generating unique IDs – java.util.UUID.randomUUID().
- Package by feature, not layer.
- return zero-length arrays instead of null.
- Arrays as String – Arrays.asList(myArray).toString().
- Compare and sort Strings – simple Unicode ordering – used by String, localized ordering (the kind expected by an end user) – used by Collator.
- There are two sources of database connections – either a DataSource or a DriverManager.
- Measure application performance -Runtime.freeMemory(), Runtime.totalMemory(), java -Xprof MyClass, java -Xrunhprof MyClass.
Examine bytecode – javap
- Generate random numbers -the java.util.Random class generates random integers, doubles, longs and so on, in various ranges. the static method Math.random generates doubles between 0 (inclusive) and 1 (exclusive).
- Use template for repeated try-catch – Use template for transactions.
- Stack trace as String – Throwable.printStackTrace(PrintWriter) or StackTraceElement class.
- Static methods cannot be overridden but can be hidden if they are not final.
- The objects created in the String pool are not subjected to GC until the class is unloaded by the JVM.
- Local classes cannot access non-final variables.
- String.trim() etc. returns the result.
- Compare TimeOfDay values (eg. hours difference) : Math.abs(Period.fieldDifference(fromTime, toTime).getHours().
- Get the current time in milliseconds – System.currentTimeMillis()
- Set the current time to return a fixed millisecond time – DateTimeUtils.setCurrentMillisFixed(milliseconds)
Feel free to add small tips and tricks.