13 April, 2012

Displaying Array as String in Java

Sometime in your code you want display array in string format.
Expected result is to display array collection as string (scalar data type) separated by comma.
Any array contains toString() method which returns informative only and doesn't contain any content of array.

For Example if I use toString() method with array
    public static void main(String[] args) {
        String[] str = new String[3];
        str[0] = "Mahmoud";
        str[1] = "Ahmed";
        str[2] = "El-Sayed";

        System.out.println(str.toString());
    } 


The output in console is
>>>>>>>>use toString() against array
[Ljava.lang.String;@9931f5



Some developers develop their own code to display array as string, But what I want to mention in this post that Java has already classes that can help you doing this.
You can use methods (deepToString() , toString() ) in  java.util.Arrays to do this.
You can see below example and see the output
    public static void main(String[] args) {
        String[] str = new String[3];
        str[0] = "Mahmoud";
        str[1] = "Ahmed";
        str[2] = "El-Sayed";
        System.out.println(">>>>>>>>use toString() against array");
        System.out.println(str.toString());
        System.out.println(">>>>>>>use java,util.Arrays.toString() method");
        System.out.println(Arrays.toString(str));
        System.out.println(">>>>>>>use java,util.Arrays.deepToString() method");
        System.out.println(Arrays.deepToString(str));
    }

The output in console is
>>>>>>>>use toString() against array
[Ljava.lang.String;@19ee1ac
>>>>>>>>use java,util.Arrays.toString() method
[Mahmoud, Ahmed, El-Sayed]
>>>>>>>>use java,util.Arrays.deepToString() method
[Mahmoud, Ahmed, El-Sayed]



For More Details, Read More in Java String Class

Thanks
Mahmoud A. El-Sayed

No comments:

Post a Comment

ADF : Scope Variables

Oracle ADF uses many variables and each variable has a scope. There are five scopes in ADF (Application, Request, Session, View and PageFl...