Posts

Showing posts with the label Java Tips

@Overrride annotation introduced in Java1.5

Whenever we have a subclass that implements parent method it is marked with annotation as @Override. This is to make compiler know that the child overrides the method defined or declared in parent. If @Overrride annotation is commented, the subclass will work as it was. But if in future, the signature of parent class changes, the compiler wont ask to implement the method instead it will think subclass has overloaded the method present in base class. If you uncomment @Override annotation, the compiler will throw compile time error as method signature in parent class has changed. Annotation should be used as standard as- It ensures that for any change in method signature of parent class, compiler will ask to change it for the subclasses.    Also it is better to resolve issue in compile time rather than runtime

Open-Closed Principle

'A class should be open for extension closed for modification.' The above principle explains that a class once defined should not be changed(closed for modification). This is because it may impact other parts of application. Hence, if modification is needed, that class behaviour should be extended and modification should be done. (open for extension) Consider a scenario where area of a shape(like rectangle, square, circle) is calculated within Main class. Now addition of any new shape will lead to change in Main class. This concludes that the Shape is tightly coupled with Main class. In order to avoid this Shape should be inherited by diff Shape classes like Rect, Triangle, Circle implementing the behaviour of calculating area() and Main class should be loosely coupled by using Shape.area() (as Triangle, Rectangle are Shape). Hence, Shape interface is contract between its concrete classes and Main class. This allows us to add new shape class without any impact on exi...

Interface Segregation Principle

'Clients should not be forced to depend upon interfaces having methods that client do not need.' This principle is closely related to Single Responsibility Principle as it supports the idea of having a specific interface than a generic purpose interface (known as 'Fat Interface' or 'Polluted Interface'). If we have a single interface having various functionality, a child implementing that interface will implement desired method along with all the other unwanted methods of that interface for no reason. An interface declaring much more work should be break down to small interfaces that specifies its purpose. This allows the child class to inherit the interface it wants, to achieve a purpose. For eg:    public interface DocumentGenerator{       public void abstract generateWordDoc( );       public void abstract generatePdf( );       public void abstract generateTxt( );    }    class ...

Single Responsibility Principle

The class should have only one reason to change. This principle overcomes the below drawbacks- If the class has more than one reason to change, Change in one area impacts the other. This makes the code more fragile (easily to break). Difficult to test and maintain. Tight coupling. Less cohesive (a class has many action) and hence not focusing on what it is suppose to do. Hence, Single responsibility boils down to high cohesion i.e. a class focus on what it should be doing (methods related to the intention of class)  

Dependency Injection Principle

Suppose there are two classes - A.java and B.java where A.java consumes B.java as below- class A{    B b = new B(); }  The above code shows that the two classes are tightly coupled and hence have following drawback- In case class A wishes to switch to another class instead of B, say class C then we need to make changes in class A which is not desireable. If A is further inherited by other classes, then change mentioned in point 1 will affect ALL the child classes.  Testing of class A will be difficult because its directly using B hence, mocking of class B is not possible.  One solution to above problem is -    class A{       B b;    } But here, we are asking the calling class to initialize class B for A, which is not a good practise. Also, it still holds above concerns. The above issue is resolved by 'Dependency Injection Princple' which states that - Two classes should be loosely coupled. This can be ...

Convert Collection to Array

1. Convert Set to Array of String           final HashMap<String, String> orderingOptionMap = new HashMap<String, String>();          orderingOptionMap.put("1", "Name: A-Z");          orderingOptionMap.put("2", "Name: Z-A");          orderingOptionMap.put("3", "Age: Ascending");          orderingOptionMap.put("4", "Age: Descending");          String[] orderingOption =   orderingOptionMap.keySet().toArray(new String[orderingOptionMap.size()]);           

Check If table exist or not

​To check if table exists or not , below is the code snippet-    import java.sql.Connection;    import java.sql.DatabaseMetaData;    import java.sql.ResultSet;     public class Main {        public static void main(String[] argv) throws Exception {          Connection c = null;          DatabaseMetaData dbm = c.getMetaData();          ResultSet rs = dbm.ge​​tTables(null, null, "employee", null);          if (rs.next()) {            System.out.println("Table exists");           } else {            System.out.println("Table does not exist");           }        }     } For Android internal memory, SQLLite -      public boolean doesTableExists(Stri...

Multiple Inheritance is not supported in Java

Below diagram explains is called Diamond Problem because of the inheritance structure.       A foo()           / \          /   \ foo() B C foo()          \   /           \ /         D foo() Multiple inheritance does cause casting, constructor chaining,etc problems. Also, multiple inheritance leads to complexity. Hence, Java do not support multiple inheritance. But recently, in JAVA 8, this problem is handled in different way, that is, the compiler will throw exception in this scenario and we will have to provide implementation logic in the class implementing the interfaces.

Java 8 Features

Java 8 has really come out to be powerful where it has improved the performance with boilerplate code with respect to collections, interface. Below are some key points- forEach() method in Iterable interface default and static methods in Interfaces Functional Interfaces and Lambda Expressions Java Stream API for Bulk Data Operations on Collections Java Time API Collection API improvements Concurrency API improvements Java IO improvements Miscellaneous Core API improvements You can have a deeper understanding in below mentioned link- http://www.journaldev.com/2389/java-8-features-with-examples https://leanpub.com/whatsnewinjava8/read  (Along with Github link) https://www.javacodegeeks.com/2014/03/8-new-features-for-java-8.html

Can main() Method be overloaded or overridden

Overloading- Any Method can be overloaded. And hence, you can overloading main() method. But JVM will always call the original main method, it will never call your overloaded main method. Overridding- Main is a static method and static method cannot be overridden in Java. Hence, its not possible to override main() method.

Can static method be overridden?

Static methods are bonded during compile time (static binding). And hence, it resolves to reference variable and not Object. And hence, you cannot override static method.     For e.g. -           Parent p = new Child();          p.callStaticMethod();    This method will invoke Parent class method and not Child class. 

Remove Duplicates from ArrayList

ArrayList implements List Interface and hence, allows duplicates. 1. The simplest approach to remove repeated objects from ArrayList is to copy them to a Set e.g. HashSet and then copy it back to ArrayList. This will remove all duplicates without writing any more code. 2. If original order of elements in ArrayList is important for you, as List maintains insertion order, you should use LinkedHashSet because HashSet doesn't provide any ordering guarantee. 3. Iterate over the ArrayList to check for duplicate and remove() it. Please Note- If you are using deleting duplicates while iterating, make sure you use Iterator's remove() method and not the ArrayList one to avoid ConcurrentModificationException.  In this tutorial we will see this approach to remove duplicates. Also, If you don't prefer converting List to Set than you can still go with copying data from one ArrayList to other ArrayList and removing duplicates by checking with ArrayList.contains() method.

Variable is accessed from within inner class needs to be declared FINAL

You can declare the variable final, or make it an instance (or global) variable. If you declare it final, you won't be able to change it later. Any variable defined in a method and accessed by an anonymous inner class must be final. Otherwise, you could use that variable in the inner class, unaware that if the variable changes in the inner class, and then it is used later in the enclosing scope, the changes made in the inner class did not persist in the enclosing scope. Basically, what happens in the inner class stays in the inner class.   Also, if two methods see the same local variable, Java wants you to swear you will not change it - FINAL, in Java speak. Together with the absence of by-reference parameters, this rule ensures that locals are only assigned in the method that they belong to. Code is thus more readable.

Static and Dynamic Binding

Its process used to link which method or variable to be called as result of there reference in code. Most of the references is resolved during compile time but some references which depends upon Object and polymorphism(overloading) in Java is resolved. Below are few differences-  1) Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime. 2) private, final and static methods and variables uses static binding and bonded by compiler while virtual methods are bonded during runtime based upon runtime object. 3) Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding. 3) Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.