-2

Whenever I run it, it prints all the lines perfectly as it's looping through with the first print statement, however when I call that last print statement, the console displays absolutely nothing. And whenever I comment out the looped print statement, the console is completely blank. Here's my code:

public static void main(String[] args){                        
    try {    
        URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=San+Antonio&destinations=San+Francisco&key="); 
        URLConnection mapcon = url.openConnection();
        BufferedReader buffreader = new BufferedReader(new InputStreamReader(mapcon.getInputStream()));
        String reqData = new String("");
        String inputLine;

        while ((inputLine = buffreader.readLine()) != null){
            reqData.concat(inputLine);
            System.out.println(inputLine);
        }

        System.out.println(reqData);
    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    [From the Java Docs](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#concat-java.lang.String-) - *"Returns: a string that represents the concatenation of this object's characters followed by the string argument's characters."* - `String` is not mutable, instead, where you attempt to mutate it, it returns a new `String` of the result of the mutation. You'd actually be better off using a `StringBuilder` – MadProgrammer Dec 30 '17 at 22:06
  • Possible duplicate of [Why doesn't my Java string concatenation work?](https://stackoverflow.com/questions/11905531/why-doesnt-my-java-string-concatenation-work) – Bernhard Barker Dec 30 '17 at 22:22

2 Answers2

1

concat() returns a string with the concatenated string value

reqData = reqData.concat(inputLine);

https://www.tutorialspoint.com/java/java_string_concat.htm

user8908459
  • 537
  • 5
  • 24
1

You forgot to update reqData after concatenation:

reqData.concat(inputLine);

Do it as:

reqData = reqData.concat(inputLine);

Also, it is not necessary to create a String with new String("");


You may consider using StringBuilder as Strings are immutable hence it creates new String objects for every concatenation.

Example of StringBuilder

StringBuilder reqData = new StringBuilder("");
reqData.append(inputLine);
user3437460
  • 17,253
  • 15
  • 58
  • 106