Wednesday 18 June 2014

join (CharSequence delimiter, Iterable elements)

public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

import static java.lang.String.join;
import java.util.*;

class StringJoin1{
 public static void main(String args[]){
  String str;
  List<String> myList;
  
  myList = new ArrayList<> ();
  
  myList.add("123");
  myList.add("234");
  myList.add("345");
  myList.add("456");
  
  str = join("-", myList);
  
  System.out.println("str = " + str);
 }
}

Output
str = 123-234-345-456

1. Throws NullPointerException If delimiter or elementsis code null.
import static java.lang.String.join;
import java.util.*;

class StringJoin1NullPointer{
 public static void main(String args[]){
  String str;
  List<String> myList;
  
  myList = new ArrayList<> ();
  
  myList.add("123");
  myList.add("234");
  myList.add("345");
  myList.add("456");
  
  str = join(null, myList);
  
  System.out.println("str = " + str);
 }
}

Output
Exception in thread "main" java.lang.NullPointerException
        at java.util.Objects.requireNonNull(Objects.java:203)
        at java.lang.String.join(String.java:2487)
        at StringJoin1NullPointer.main(StringJoin1NullPointer.java:16)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment