Sunday, 14 February 2016

Data types in JAVA

Data types:
        In java every variable has a type and every expression should have a type, every type is strictly defined. All variable assignments must be checked by the compiler for type compatibility hence java is considered as strongly typed language
byte à Capacity : 1 byte  Range: -128 to +127
    It is best suitable for file transfers via networks 
short à capacity : 2 bytes Range: -215 to +215 -1
    it is best suitable for 16 bit processors.
int à capacity : 4 bytes  Range: -231 to +231 - 1
   In C language int capacity varies platform to plat form. Hence C  program results varies from platform to platform. Where as in JAVA int capacity is constant irrespective to platform.
long à capacity : 8 bytes Range: -263 to +263 -1
     if any integer value excessed  int value then we will go got long data type
float à Capacity : 4 bytes Range: -3.4e38 to +3.4e38 -1
   if we wants to consider to 7 decimal of accuracy we will go for float
double à Capacity : 8 bytes Range: -1.7e308 to +1.7e308 -1
   if we wants to consider to 15 decimal of accuracy we will go for double. Float and double types are best suitable for mediacl operators, satellite operations….
char à Capacity: 2 bytes. Range 0 to 65535 (no –ve values)
boolean à the capacity is virtual. No capacity and range

   In c language 1 represents true 0 represents false. But in JAVA we have literals true & false

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"}

Java Programming Tips and Best Practices for Beginners - Part2

6. Check Oddity
Have a look at the lines of code below and determine if they can be used to precisely identify if a given number is Odd?
public boolean oddOrNot(int num) {
return num % 2 == 1;
}
These lines seem correct but they will return incorrect results one of every four times (Statistically speaking). Consider a negative Odd number, the remainder of division with 2 will not be 1. So, the returned result will be false which is incorrect!
This can be fixed as follows:
public boolean oddOrNot(int num) {
return (num & 1) != 0;
}
Using this code, not only is the problem of negative odd numbers solved, but this code is also highly optimized. Since, Arithmetic and Logical operations are much faster compared to division and multiplication, the results are achieved faster so in second snippet.
7. Difference between single quotes and double quotes
public class Haha {
public static void main(String args[]) {
System.out.print("H" + "a");
System.out.print('H' + 'a');
}
}
From the code, it would seem return “HaHa” is returned, but it actually returns Ha169. The reason is that if double quotes are used, the characters are treated as a string but in case of single quotes, the char -valued operands ( ‘H’ and ‘a’ ) to int values through a process known as widening primitive conversion. After integer conversion, the numbers are added and return 169.
8. Avoiding Memory leaks by simple tricks
Memory leaks often cause performance degradation of software. Since, Java manages memory automatically, the developers do not have much control. But there are still some standard practices which can be used to protect from memory leakages.
•           Always release database connections when querying is complete.
•           Try to use finally block as often possible.
•           Release instances stored in Static Tables.
9. Avoiding Deadlocks in Java
Deadlocks can occur for many different reasons. There is no single recipe to avoid deadlocks. Normally deadlocks occur when one synchronized object is waiting for lock on resources locked by another synchronized object.
Try running the below program. This program demonstrates a Deadlock. This deadlock arises because both the threads are waiting for the resources which are grabbed by other thread. They both keep waiting and no one releases.
01      public class DeadlockDemo {
02           public static Object addLock = new Object();
03           public static Object subLock = new Object();
04       
05           public static void main(String args[]) {
06       
07              MyAdditionThread add = new MyAdditionThread();
08              MySubtractionThread sub = new MySubtractionThread();
09              add.start();
10              sub.start();
11           }
12        private static class MyAdditionThread extends Thread {
13              public void run() {
14                 synchronized (addLock) {
15                int a = 10, b = 3;
16                int c = a + b;
17                    System.out.println("Addition Thread: " + c);
18                    System.out.println("Holding First Lock...");
19                    try { Thread.sleep(10); }
20                    catch (InterruptedException e) {}
21                    System.out.println("Addition Thread: Waiting for AddLock...");
22                    synchronized (subLock) {
23                       System.out.println("Threads: Holding Add and Sub Locks...");
24                    }
25                 }
26              }
27           }
28           private static class MySubtractionThread extends Thread {
29              public void run() {
30                 synchronized (subLock) {
31                int a = 10, b = 3;
32                int c = a - b;
33                    System.out.println("Subtraction Thread: " + c);
34                    System.out.println("Holding Second Lock...");
35                    try { Thread.sleep(10); }
36                    catch (InterruptedException e) {}
37                    System.out.println("Subtraction  Thread: Waiting for SubLock...");
38                    synchronized (addLock) {
39                       System.out.println("Threads: Holding Add and Sub Locks...");
40                    }
41                 }
42              }
43           }
44        }
Output:
1          =====
2          Addition Thread: 13
3          Subtraction Thread: 7
4          Holding First Lock...
5          Holding Second Lock...
6          Addition Thread: Waiting for AddLock...
7          Subtraction  Thread: Waiting for SubLock...
But if the order in which the threads are called is changed, the deadlock problem is resolved.
01        public class DeadlockSolutionDemo {
02           public static Object addLock = new Object();
03           public static Object subLock = new Object();
04       
05           public static void main(String args[]) {
06       
07              MyAdditionThread add = new MyAdditionThread();
08              MySubtractionThread sub = new MySubtractionThread();
09              add.start();
10              sub.start();
11           }
12       
13       
14        private static class MyAdditionThread extends Thread {
15              public void run() {
16                 synchronized (addLock) {
17                int a = 10, b = 3;
18                int c = a + b;
19                    System.out.println("Addition Thread: " + c);
20                    System.out.println("Holding First Lock...");
21                    try { Thread.sleep(10); }
22                    catch (InterruptedException e) {}
23                    System.out.println("Addition Thread: Waiting for AddLock...");
24                    synchronized (subLock) {
25                       System.out.println("Threads: Holding Add and Sub Locks...");
26                    }
27                 }
28              }
29           }
30           
31           private static class MySubtractionThread extends Thread {
32              public void run() {
33                 synchronized (addLock) {
34                int a = 10, b = 3;
35                int c = a - b;
36                    System.out.println("Subtraction Thread: " + c);
37                    System.out.println("Holding Second Lock...");
38                    try { Thread.sleep(10); }
39                    catch (InterruptedException e) {}
40                    System.out.println("Subtraction  Thread: Waiting for SubLock...");
41                    synchronized (subLock) {
42                       System.out.println("Threads: Holding Add and Sub Locks...");
43                    }
44                 }
45              }
46           }
47        }
Output:
1          =====
2          Addition Thread: 13
3          Holding First Lock...
4          Addition Thread: Waiting for AddLock...
5          Threads: Holding Add and Sub Locks...
6          Subtraction Thread: 7
7          Holding Second Lock...
8          Subtraction  Thread: Waiting for SubLock...
9          Threads: Holding Add and Sub Locks...
10. Reserve memory for Java
Some of the Java applications can be highly CPU intensive as well as they need a lot of RAM. Such applications generally run slow because of a high RAM requirement. In order to improve performance of such applications, RAM is reserved for Java. So, for example, if we have a Tomcat webserver and it has 10 GB of RAM. If we like, we can allocate RAM for Java on this machine using the following command:
1          export JAVA_OPTS="$JAVA_OPTS -Xms5000m -Xmx6000m -XX:PermSize=1024m -XX:MaxPermSize=2048m"
•           Xms = Minimum memory allocation pool
•           Xmx = Maximum memory allocation pool
•           XX:PermSize = Initial size that will be allocated during startup of the JVM

•           XX:MaxPermSize = Maximum size that can be allocated during startup of the JVM

Java Programming Tips and Best Practices for Beginners-Part 1

1. Prefer returning Empty Collections instead of Null
If a program is returning a collection which does not have any value, make sure an Empty collection is returned rather than Null elements. This saves a lot of “if else” testing on Null Elements.
public class getLocationName {
    return (null==cityName ? "": cityName);
}
2. Use Strings carefully
If two Strings are concatenated using “+” operator in a “for” loop, then it creates a new String Object, every time. This causes wastage of memory and increases performance time. Also, while instantiating a String Object, constructors should be avoided and instantiation should happen directly. For example:
//Slower Instantiation
String bad = new String("Yet another string object");
//Faster Instantiation
String good = "Yet another string object";

3. Avoid unnecessary Objects
One of the most expensive operations (in terms of Memory Utilization) in Java is Object Creation. Thus it is recommended that Objects should only be created or initialized if necessary. Following code gives an example:
import java.util.ArrayList;
import java.util.List;

public class Employees {
private List Employees;
public List getEmployees() {
//initialize only when required
if(null == Employees) {
                  Employees = new ArrayList();
}
          return Employees;
}
}
4. Dilemma between Array and ArrayList
Developers often find it difficult to decide if they should go for Array type data structure of ArrayList type. They both have their strengths and weaknesses. The choice really depends on the requirements.
import java.util.ArrayList;
public class arrayVsArrayList {
public static void main(String[] args) {
int[] myArray = new int[6];
myArray[7]= 10; // ArraysOutOfBoundException
//Declaration of ArrayList. Add and Remove of elements is easy.
ArrayList<Integer> myArrayList = new ArrayList<>();
myArrayList.add(1);
myArrayList.add(2);
myArrayList.add(3);
myArrayList.add(4);
myArrayList.add(5);
myArrayList.remove(0);
for(int i = 0; i < myArrayList.size(); i++) {
System.out.println("Element: " + myArrayList.get(i));
}
//Multi-dimensional Array
int[][][] multiArray = new int [3][3][3];
}
}
1.       Arrays have fixed size but ArrayLists have variable sizes. Since the size of Array is fixed, the memory gets allocated at the time of declaration of Array type variable. Hence, Arrays are very fast. On the other hand, if we are not aware of the size of the data, then ArrayList is more data will lead to ArrayOutOfBoundException and less data will cause wastage of storage space.
2.         It is much easier to Add or Remove elements from ArrayList than Array
3.         Array can be multi-dimensional but ArrayList can be only one dimension.
5. When Finally does not get executed with Try
Consider following code snippet:
public class shutDownHooksDemo {
public static void main(String[] args) {
for(int i=0;i<5;i++)
{
try {
if(i==4) {
System.out.println("Inside Try Block.Exiting without executing Finally block.");
System.exit(0);
}
}
finally {
System.out.println("Inside Finally Block.");
}
}
}
}
From the program, it looks like “println” inside finally block will be executed 5 times. But if the program is executed, the user will find that finally block is called only 4 times. In the fifth iteration, exit function is called and finally never gets called the fifth time. The reason is- System.exit halts execution of all the running threads including the current one. Even finally block does not get executed after try when exit is executed.
When System.exit is called, JVM performs two cleanup tasks before shut down:
First, it executes all the shutdown hooks which have been registered with Runtime.addShutdownHook. This is very useful because it releases the resources external to JVM.
Second is related to Finalizers. Either System.runFinalizersOnExit or Runtime.runFinalizersOnExit. The use of finalizers has been deprecated from a long time. Finalizers can run on live objects while they are being manipulated by other threads. This results in undesirable results or even in a deadlock.
public class shutDownHooksDemo {
public static void main(String[] args) {
for(int i=0;i<5;i++)
           {
                  final int final_i = i;
                  try {
                          Runtime.getRuntime().addShutdownHook(new Thread() {
                                                                 public void run() {
                                                                            if(final_i==4) {
System.out.println("Inside Try Block.Exiting without executing Finally block.");
System.exit(0);
}
}
});
}
finally {
System.out.println("Inside Finally Block.");
}
}
}
}

Tuesday, 9 February 2016

OOP’s Concepts in JAVA

Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:

v  Object
v  Class
v  Inheritance
v  Polymorphism
v  Abstraction
v  Encapsulation

Object:
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
Class:
Collection of objects is called class. It is a logical entity.
Example:
public class ClassAndObjectDemo {

      public static void main(String[] args) {
            // Creation of an Object. we can creates n number of Objects for a single class
            Sample s = new Sample();
      }
}
class Sample{// class
      int i;
      float j;
      Sample(){
            System.out.println("Sample Class Constructor");
      }
      void m1(){
            System.out.println("sample class m1");

      }
}

Important Point:
1.  For creating an object we are using a 'new' operator
        2. Each object will have all the features of a class

Abstraction:

If we want to hide the implementation to the outside world we are using abstraction. With this technique we are providing security to our implementation.
In JAVA we are achieving this abstraction in two ways
1.       By creating abstract class
2.       By creating Interface

Abstract class:
    An abstract class is a class which will have abstract methods and concrete methods.
            Abstract method: This is a method without implementation
            Concrete method: This is a method which will have implementation
    Ex: Abstract class and its allowed elements in an abstract class

public abstract class AbstractClassDemo {
      // we can create instance variables
      int i;
      int j;
      // we can create constants
      final int k=10;
      // we can create a constructor for abstract class
      public AbstractClassDemo() {
            System.out.println("AbstractClassDemo Constructor");
      }
      // abstract method
      abstract void m1();
      //concrete method
      private void m2(){
           
      }
      // we can write a main method
      public static void main(String[] a){
            System.out.println("Raju");
      }
Important Points:
1.       We are not allowed to create an object for abstract class but we can creates reference to abstract class
   Ex: AbstractClassDemo aCD = new AbstractClassDemo(); // Wrong        
 AbstractClassDemo aCD; // it allowed. Here we are just creating reference
2.       We can’t create object for the abstract class.
3.       We can create reference variable for abstract class.
4.       If a class contains abstract method then we should declare that class as an abstract class.
5.       We can extend abstract class to another class.
6.       If extended class also having abstract class then that class also should declared as abstract class.
7.       Abstract class may contain zero no.of abstract methods. This is for avoiding object creation.

Interfaces:
   An interface will have only abstract methods. So we can call this interface is a fully abstract class
Ex: Interface and allowed elements
public interface InterfaceDemo {
      //we can declare constants
      // if we are not declare "public final static" for constants then compiler by default includes
      public final static int CONSTANT_ONE = 1;
      // if we are not declare "public abstract" for methods then compiler by default includes
      public abstract void methodOne();
      public abstract int methodTwo();
}
Important Points:
1.       We are not allowed to create an object for abstract class but we can creates reference to abstract class
   Ex: InterfaceDemo iD = new InterfaceDemo ();
         
 InterfaceDemo iD;it allowed. Here we are just creating reference

2.       We never highlight our implementation to the outside world so we can achieve security for our implementation.
3.       Interface contains 100% abstract methods.
4.       We can declare constants.
5.       By default these constants ‘public static final’.
6.       By default methods have ‘public abstract’

Inheritance:

   If we want to acquire all the features from other component into our component we will go for inheritance. In JAVA we can achieve this inheritance in two ways
1.       By extending a class : For this we are using “extends” keyword
Ex:
public class ExtendsDemo extends Sample{
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            Sample s = new Sample();
            s.method1();
      }
}
class Sample{
      int method1(){
            System.out.println("I am Sample method1");
            return 'a';
      }
}

Important Points:
1.       We can extend only one class to another class.
     Ex:
            class ExtendsDemo extends Sample
      class ExtendsDemo extends Sample,Sample1
               class ExtendsDemo extends Sample extends Sample1

2.       We can’t achieve multiple inheritance in JAVA using classes because of ambiguity problem

2.    By implementing an interface : 
For this we are using “implements” keyword 
 Ex:

public interface InterfaceDemo {
      //we can declare constants
      // if we are not declare "public final static" for constants then compiler by default includes
      public final static int CONSTANT_ONE = 1;
      // if we are not declare "public abstract" for methods then compiler by default includes
      public abstract void methodOne();
      public abstract void methodTwo();
}
class ImplementsDemo implements InterfaceDemo{
      public void methodOne(){
            System.out.println("methodOne Implementation");
      }
      // if we are not interested to provide implementation then we should provide an empty implementation at least
      public void methodTwo(){

      }
}

Important Points:
1.       We can achieve multiple inheritance by using interfaces
Ex:
class ImplementsDemo implements InterfaceDemo1,InterfaceDemo2
class ImplementsDemo implements InterfaceDemo1 implements InterfaceDemo2class ImplementsDemo extends Sample implements InterfaceDemo2

Polymorphism:
Polymorphism means one thing is in many ways. In JAVA we can achieve in two ways
1.      By using method overloading
Ex:
public class MethodOverLoadingDemo {
      // this is called overloading method
      public void methodOne(int i){
            System.out.println("I am MethodOverLoadingDemo methodOne()-->"+i);
      }
}
class MethodOverloadingImpl extends MethodOverLoadingDemo{
      public static void main(String[] args) {
            // calling child class method with child class reference with child class object
            MethodOverloadingImpl methodOverloadingImpl= new MethodOverloadingImpl();
            methodOverloadingImpl.methodOne();
            //calling parent class method with child class reference with child class object
            methodOverloadingImpl.methodOne(0);
            // calling child class method with parent class reference with child class object
            // In method Overloading method calls will be decides based on reference not on based on created object
            MethodOverLoadingDemo methodOverLoadingDemo = new MethodOverloadingImpl();
            methodOverLoadingDemo.methodOne(0);
            //methodOverLoadingDemo.methodOne(); -- this is not possible
      }
      // this is overloaded method
      public void methodOne() {
            System.out.println("I am MethodOverloadingImpl methodOne");

      }
}

Output:

I am MethodOverloadingImpl methodOne
I am MethodOverLoadingDemo methodOne()-->0
 I am MethodOverLoadingDemo methodOne()-->0

Important Points:
1.       This is called static polymorphism.
2.       All the method calls will decides based on references not based on objects
3.       Two methods are said to be overloaded if they have the same method names but different parameter list (At least order).
4.       We never consider return type, access modifier and throws clause in overloading.
5.       In method overloading, which method need to call decided by the compiler at compile time. So overloading is called “static polymorphism” OR “early binding”


2.      Method Overriding
Ex:
public class MethodOverridingDemo {
      //This is overriding method
      public int methodOne(){
            System.out.println("I am MethodOverridingDemo methodone()");
            return 10;
      }
}
class MethodOverridingImpl extends MethodOverridingDemo{
      //This is overridden method
      // In method Overriding method signature should be same
      public int methodOne() {
            System.out.println("I am MethodOverridingImpl methodOne()");
            // return value can be different data type which can be internally promoted to declared data type
            return 'a';
      }
      public static void main(String[] args) {
            // calling child class method with child class reference with child class object
            MethodOverridingImpl methOverridingImpl = new MethodOverridingImpl();
            methOverridingImpl.methodOne();
            // calling child class method with Parent class reference with child class object
            // In method Overriding method calls will be decides based on created object not based on reference
            MethodOverridingDemo methodOverridingDemo = new MethodOverridingImpl();
            methodOverridingDemo.methodOne();
           
      }
}

Output:

I am MethodOverridingImpl methodOne()
I am MethodOverridingImpl methodOne() 

Important Points:
1.       In overriding the method names and arguments (including order must be same).
2.       In case of overriding signatures of the methods must be same.
3.       Access modifier incremental is allowed in method overriding.
4.       An abstract method can be overridden as non-abstract method
5.        While overriding we can’t increase the no.of checked exceptions & we can‘t directly use parent exception.
6.       There is no rule for unchecked exceptions


Encapsulation:

  Encapsulation means bundling the data into a one unit. In JAVA we have two types of encapsulations
1.       Partial encapsulation : class is the best example for partial encapsulation because a call can contains all kinds of elements with all kinds of access modifiers
2.       Fully encapsulation: JAVA bean is the best example for full encapsulation because all the members are private and getters and setters are public access modifiers

         Ex: Bean example
public class JavaBeanDemo {

       private int sno;
       private String sname;
       public int getSno() {
              return sno;
       }
       public void setSno(int sno) {
              this.sno = sno;
       }
       public String getSname() {
              return sname;
       }
       public void setSname(String sname) {
              this.sname = sname;
       }
}

Important Points:
1.       All the members should be private
2.       Setters don’t have return type
3.       Setters have private access
4.       Getters have public access modifier
5.       Getters have return type of corresponding data member data type declared
6.       Getters have return type whereas setters don’t
7.       Setters have parameter whereas getter doesn’t