Monday, December 5, 2016

JAVA Tips and Gotchas.


  • Overloading - if the number of parameters are different, the return type can be different. But the return type cannot be used to differentiate the methods.
  • Static blocks is executed when the class is first loaded before the class can be used anywhere else, and thus can be used to initialize members before the class is constructed.
  • Recursive versions of many routines may execute a bit more slowly than their iterative equivalents because of the additional overhead of the additional method calls.
  • Inner class - a class inside a class but outside of any method.
  • Nested class - a class inside a method.
  • Autoboxing - occurs when a primitive type must be converted into an object. Vice versa, auto-unboxing happens whenever an object must be converted into a primitive type. (Say, between int and Integer)
  • Use 'import static' - called static import - to refer to static members of a class directly by their names, without  having to qualify them with the class name.
  • @Annotation (Metadata) - used by frameworks in development and deployment.
    • @Retention
    • @Target
    • @Inherited
    • @Override
    • @Deprecated
    • @SafeVarargs
    • @SuppressWarnings
    • @FunctionalInterface
  • In Java 8, you can specify a variable-length argument (varargs) by three periods (...)
Example
// If mixing normal and varargs parameters, the variable-length
// parameter must be the only and the last one.
static void myVarMethod (int a, double b, String c, int ... v) {
   for ( int i=0; i < v.length; i++ ) {
      system.out.println ("index-" + i + " = " + v[i]);
   }
}

public void main (String args[]) {
   myVarMethod (5, 1, 3);
   myVarMethod (2);
   myVarMethod ();
}


import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
// Not a good practice as out.println is now ambiguous
import static java.lang.System.out;

// Now you can call these methods directly
double x = sqrt (pow(a, 4) - b*c);
double x = (-b + sqrt (pow(b, 2) - 4*a*c)) / (2*a);
out.println ("The solution is ", + x);


Java Generics
class ClassGeneric  {
   T obj;

   ClassGeneric (T o) {
      this.obj = o;
   }

   T getObj() {
      return obj;
   }

   void printType () {
      System.out.println ("Type of this object is " + 
         obj.getclass().getName() );
   }
}

// To use ClassGeneric
class Demo {
   public static void main (String args[]) {
      ClassGeneric  instanceOfT;
      instanceOfT = new ClassGeneric  (23);
      instanceOfT.printType();

      ClassGeneric  instanceOfStr = new ClassGeneric ("My String");
      instanceOfT.printType();
   }
}



No comments:

Post a Comment