Home > Back-end >  Java: Why Strings in a 2D Array are not enclosed in "" Double Quotes
Java: Why Strings in a 2D Array are not enclosed in "" Double Quotes

Time:07-11

I am trying to create a 2D List of Strings.

import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        int columns = 2;
        int rows = 2;
    
        String[][] newArray = new String[columns][rows];
        newArray[0][0] = "One";
        newArray[0][1] = "Two";

        newArray[1][0] = "Three";
        newArray[1][1] = "Four";

        System.out.print(Arrays.deepToString(newArray));
}
}

Output:

[[One, Two], [Three, Four]]

Above each string is not enclosed in double quotes due to which api is rejecting my data. Can someone help to make output like below

[["One", "Two"], ["Three", "Four"]]

CodePudding user response:

Java is not rendering the surrounding quotes because such quotes do not exist in the character sequence, or string, that you've defined. To include a double quote character in the string, you can escape the character using \. For example...

String[][] newArray = new String[columns][rows];
newArray[0][0] = "\"One\"";
newArray[0][1] = "\"Two\"";

newArray[1][0] = "\"Three\"";
newArray[1][1] = "\"Four\"";

If you want to communicate with an API that expects data to be in the JSON data format, then I recommend you look into purpose-built libraries such as Jackson.

CodePudding user response:

because newArray accept as a String

    newArray[0][0] = "One";
    newArray[0][1] = "Two";

    newArray[1][0] = "Three";
    newArray[1][1] = "Four";

To include a double quote in a string, you can escape the character using " \ ". like

     newArray[0][0] = "\"One\"";
     newArray[0][1] = "\"Two\"";
  • Related