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

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.


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);

Value of x = 1
Value of y = 3

Sample code:


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);


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.