Sunday, 26 June 2016

final keyword in java

Keyword 'final' says all about itself.
If you declare anything as final in java that means you can never modify it in future. Never.

Let's look at the ways in which final keyword is utilized in java.
  • Final can be used with variables to give it a permanent value (declare constant) to be utilized by others who wants to use this variable in any way and anywhere. 
  • Suppose you are creating a maths question on circle, and you want your students to use the value of pi(π) as 3.14159 in all the formula's that make use of pi. So what you can do is declare this pi as final variable and assign it the value and none of your student would be able to change this value during exam. (Now what if I declare a final variable but don't assign it a value?)
  • Final can be used with class to prevent it from being inherited by any of its sub-class. 
  • Final can be used with methods to prevent it from being overridden.

Note : Out of curiosity if you want to try and change the value of final variable or inherit a final class or override a final method then I am with you. Lets go ahead and see what we get :) 


Lets try to change final variable


final variables have the following properties:

  • final variables cannot be reinitialized once assigned a value.
  • final reference variables cannot refer to a different object once the object has been assigned to the final variable.
  • final reference variables must be initialized before the constructor completes.


public class FinalVariable {

public static void main(String[] args) {
final double pi = 3.14159;
pi = 3.14;        // You will get comile-time error saying : The final local                                                                             variable pi cannot be assigned. It must be blank and not                                                                           using a compound assignment
...................................
  ...................................
  ...................................

}

}

Check you understanding :

final int z = 4;
int y = z++;
What is the fate of this code? Would it compile?
No is the simple answer.

Be careful with this kind of code that use the increment/decrement operators on
a final variable. As you are aware by now that final variables can't be changed, the increment and decrement operators can't be used with them, and any attempt to do so will result in a compiler
error.

Don't forget : final variable value cannot be changed and they are used to declare CONSTANT.  


Lets try to inherit final class

FinalClass.java

public final class FinalClass {
        public void simpleInterest() {
        int p = 1000;
        int r = 5;
        int t = 2;

        int si = (p*r*t)/100;
        System.out.println(si);
        }
}

Now interest.java tries to extend FinalClass

public class interest extends FinalClass {         // compile-time error The type interest cannot                                                                                                     subclass the final class FinalClass
}

Written this much. Wait!
Can you see red line on the FinalClass(we have back-grounded it red here) in your Eclipse IDE which you are trying to inherit(extend). Put the cursor on this word to see the compile-time error shown above.

So the conclusion is compile time error will follow if you try to extend a class that is declared final.


Lets try to override final method

FinalClass.java

public class FinalClass {
        final void simpleInterest() {
        int p = 1000;
        int r = 5;
        int t = 2;

        int si = (p*r*t)/100;
        System.out.println(si);
        }
}

Now interest.java tries to override simpleInterest() of FinalClass

public class interest extends FinalClass {         
        void simpleInterest() {         // compile-time error The type interest cannot                                                                                                     override the final simpleInterest()
        }
}

So the conclusion is compile time error will follow if you try to override final method.

                                                                                                                                              
Q) Why would you ever mark a class final, if you can't change value of final variable, inherit final class or override final method?

You should make a final class only if you need an absolute guarantee that none of the methods in that class will ever be overridden. If you're deeply dependent on the implementations of certain methods, then using final gives you the security that nobody can change the implementation out from under you.

You'll notice many classes in the Java core libraries are final. For example, the String class cannot be subclassed. Use final for safety, but only when you're certain that your final class has indeed said all that ever needs to be said in its methods. Marking a class final means, in essence, your class can't ever be improved upon, or even specialized, by another programmer.
Suggestion : So unless you have a serious safety or security issue, assume that some day another programmer will need to extend your class.
                                                                                                                                                

You may also want to know about:


Thursday, 2 June 2016

Benefit of having non final class

Imagine you find a problem with a method in a class you're using, but you don't have the source code.

So you can't modify the source to improve the method, but you can extend the class and override the method in your new subclass, and substitute the subclass everywhere the original super class is expected.

If the class is final, though, then you're stuck.


Tuesday, 10 May 2016

Splitting a String at delimiter in Java


Scenario : Suppose we have a String separated by pipeline ( | ). For example consider,
Given String : Learn|Java|Like|Never|Before
Requirement : Break the string at |
Expected Output :  Learn
                                 Java
                                 Like
                                 Never
                                 Before


Solution :  There are different ways of doing it. Lets look at each of them one by one.
1) Using StringTokenizer : If you want to use this approach then first thing you need to do is to import java.util.StringTokenizer. Lets have a look at the below screenshot.

split String at delimiter using StringTokenizer























Few things that we need to discuss here is:

  • StringTokenizer s1_token = new StringTokenizer(s1, "|");                                                       Here we pass the String object s1 (which needs to be broken) and then delimiter | (where it needs to be broken) into the StringBuilder. And it breaks the original string  Learn|Java|Like|Never|Before at the provided delimiter into small tokens of Learn, Java, Like, Never, Before. These tokens are stored in variable s1_token.
  • s1_token.hasMoreTokens()                                                                                                           This helps in checking if more tokens are present or not. While loop executes till tokens are present in s1_token.
  • s1_token.nextToken()                                                                                                                     This fetches the stored tokens from s1_token starting from first to last, one by one and each time the value is stored in String s2 and printed as shown in the output.                                         
--------------------------------------------------------------------------------------------------------------------------

2) Using split() method : Use of split() method is generally preferred over StringTokenizer() to split the string. Reason being StringTokenizer() is a legacy method and is generally kept for compatibility reason.

Split String at the delimiter using split()



















Few things that needs to be discussed here is :

  • split() - split(String regex) splits the String around matches of the given regular expression. And the result will be stored in String array.
    Another version of this method is split(String regex, int limit)
  • use of "\\" in split() - In previous example we just used | and the task was done. Then why use \\? Nice question. If you are asking this question then you are surely trying to learn. So the answer of your question is split method takes regular expression as parameter and hence to break the string on | (or any other special character) remember to use \ to escape individual special character.
    Suppose you have Hello^World and you want to break at ^ using split. So use split("\\^")
  • //String[] s2 = s1.split(Pattern.quote("|")); - You can also use this one instead of String[] tokens = s1.split("\\|"); for the purpose. If you are using this one then don't forget to import java.util.regex.Pattern, otherwise you will get compile time error.

Note : Don't just go through the code rather code yourself and experiment to understand better. If you have query feel free to ask.


You might also want to know about:


Saturday, 7 May 2016

finalize() method in java

finalize() method is linked with garbage collection in java.
Suppose there is an object and you want some code (or perform some task) to run before that object is collected by garbage collector. You can put that code in the finalize() that all class will inherit from class Object. It means finalize() is defined in java.lang.Object class.
Note : The task might be of releasing any system resource or closing some connection that is left open. 

For any given object, finalize() is called only once(at most) by garbage collector before the object is about to get garbage collected. Now if the object somehow revives itself during this call then finalize would not be called gain.

Issues with finalize()
It might seem a good idea to depend on finalize() and put some code inside it and rest assured that it would run before the object gets garbage collected. It's good until you come to know that its not guaranteed that finalize would be called by garbage collector or when it will be called by garbage collector. Sometimes it may also happen that object has to wait indefinitely before its finalize is called. Now lets assume that finalize gets called but then again there is no guarantee that object would immediately get recollected. Hence the time of execution of code inside finalize() remains suspicious. And the timing may vary from JVM to JVM. Thus relying on finalize() doesn't seems to be a good idea.

Declaration : 
protected void finalize()

finalize() is declared as protected but why is something whose answer I am still searching...

Monday, 2 May 2016

Difference between i++ and ++i in java

Lets take, int i = 100;

Keep track on the values of i and x...

And now try to concentrate on the difference between i++ (post increment) and ++i (pre-increment),

Post increment

int x = i++;
Here value of i will first be assigned to the variable x and then its original value will be incremented. That's why its referred to as post increment operation which means do the task first and then increment.

So, x = 100, because value of i is assigned to x first and then i++ happens and the value of i is incremented by 1. Thus i = 101.


Preincrement

int x = ++i;
Here value of i will first be incremented by 1 and then the incremented value will be assigned to x.
That's why its referred to as pre-increment operation which means increment the value first and then perform the task with incremented value.

So, x = 101, because the value of i is incremented first and then assigned to x.
And obviously, i = 101.

Go through the example to develop better understanding :

Find the value of x when i = 1;

1)             int i = 1;
int x = i++;    // here value of, x = 1 and i = 2

int y = ++i;    // Now value of i=2 so ++i will increment the i(=3) by 1 and assign it to y(=3)
        System.out.println("Value of x = "+ x);
        System.out.println("Value of y = "+ y);

OUTPUT :
Value of x = 1
Value of y = 3


Sample code:

SourcePrePostIncrementOperator.java


package basic;

public class PrePostIncrementOperator {

      public static void main(String[] args) {
            int i = 0, j=0;
            int x = i++;  //Here i=1 but x=o(initial value of i)
            System.out.println("x: "+ x +" i: "+ i); 
           
            int y = ++j;
            System.out.println("y: "+ y +" j: "+j);
      }

}


OUTPUT:
x: 0 i: 1
y: 1 j: 1


So in both the case we see that value of the variable(i&j) is getting incremented. The difference is in the process of assigning the value.
i++ assigns non-incremented value to x. whereas
++j assigns the incremented value to y.

Hope I have been able to explain the concept clearly to you. Whats your thought or query about the topic? 

Please write it in the comment box.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.