URLEncoder Encodes Form Query Values

URLEncoder encodes query values with StandardCharsets.UTF_8 so spaces become plus signs and structural characters stay escaped in the query string.

JavaData Fetching

Code

snippet
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class QueryBuilder {

    public static void main(String[] args) {
        // & and = are query-string structure chars; values must escape them
        String encoded = URLEncoder.encode("blue shoes & more", StandardCharsets.UTF_8);
        System.out.println("value: " + encoded);

        // spaces encode as +: a form/query convention; URL paths use %20 instead
        System.out.println("plus: " + URLEncoder.encode("a b", StandardCharsets.UTF_8));

        // a literal plus is encoded too, removing the space ambiguity
        System.out.println("plus char: " + URLEncoder.encode("c++", StandardCharsets.UTF_8));

        // decoding reverses it: + becomes a space again
        System.out.println("decoded: " + URLDecoder.decode(encoded, StandardCharsets.UTF_8));
    }
}

What the demo escapes

The value blue shoes & more encodes under UTF-8 into blue+shoes+%26+more: the space becomes a plus, and the ampersand, a query-string structure character, turns into %26 so it cannot split parameters.

The special cases get their own lines: a plain space prints a+b, while the literal plus in c++ encodes to c%2B%2B so it cannot be mistaken for an encoded space. URLDecoder.decode reverses the whole thing, printing the original text back.

Caveats and details

    • only means space inside form/query contexts.
  • Always pass an explicit charset; the single-arg overload is deprecated.

Interactive Tools for This Topic

FAQ

Why does a literal plus need escaping?
Because decoders turn + into a space; encoding c++ as c%2B%2B keeps the plus characters intact, as the printed plus char line demonstrates.