code: public static String escape(String str) {
          int i, max;
          StringBuilder result;
          char c;
  
          max = str.length();
          for (i = 0; i < max; i++) {
              if (str.charAt(i) < 32) {
                  break;
              }
          }
          if (i == max) {
              return str;
          }
          result = new StringBuilder(max + 10);
          for (i = 0; i < max; i++) {
              c = str.charAt(i);
              switch (c) {
                  case '\n':
                      result.append("\\n");
                      break;
                  case '\r':
                      result.append("\\r");
                      break;
                  case '\t':
                      result.append("\\t");
                      break;
                  case '\\':
                      result.append("\\\\");
                      break;
                  default:
                      if (c < 32) {
                          result.append("\\u").append(Strings.padLeft(Integer.toHexString(c), 4, '0'));
                      } else {
                          result.append(c);
                      }
              }
          }
          return result.toString();
      }
docs: escape Strings as in Java String literals