/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

class Test{
   public static void main(String args[]){
      String Str = new String("WelcometoTutorialspoint.com-");
      int i=0;

      System.out.println("Return Value :" );
      for (String retval: Str.split("-", 2)){
         System.out.println(retval);
         System.out.println(i);
         i++;
      }
      i=0;

      System.out.println("");
      System.out.println("Return Value :" );
      for (String retval: Str.split("-", 3)){
         System.out.println(retval);
          System.out.println(i);
         i++;
      }

      i=0;
      System.out.println("");
      System.out.println("Return Value :" );
      for (String retval: Str.split("-", 0)){
         System.out.println(retval);
          System.out.println(i);
         i++;
      }
      System.out.println("");
      i=0;

      System.out.println("Return Value :" );
      for (String retval: Str.split("-")){
         System.out.println(retval);
          System.out.println(i);
         i++;
      }
   }
}

In this, my delimiter is at the end. In last two cases , loop is running only for 1 time but in first 2 cases it is running for 2 times each. Why is it so??

Secondly, what is the measning of passing value zero to the second field of spilt function? Thanks.

From the Java docs (emphasis mine):

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

The one-argument version of split is equivalent to the two-argument version with n being zero.

Thanks. But, can you explain it with my example. It is my first code in Java. I dnt have much idea about Java.

I'm not sure what's left to be explained. In your example the third case calls split with zero as the second argument and in the fourth case you call it with no second argument. As documented this causes trailing empty strings to be discarded.

Yup. Thanks. It helped. :) Love you Daniweb.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.